Default value is not stored in model - django

class Movie(models.Model):
image = models.ImageField(default='default.jpg')
title = models.CharField(max_length=255)
release_year = models.IntegerField()
number_in_stock = models.IntegerField()
daily_rate = models.FloatField()
genre = models.CharField(max_length=255)
date_created = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
Admin interface
The above code is my models class and i have given a default value to the
ImageField .
After saving the data my image field is still empty.
Whats the prooblem ?

Have you added this in your setting.py :
STATIC_URL = '/static/'
STATICFILES_DIRS=[
os.path.join(BASE_DIR,'static')
]
Also, you will have to add the image in the static folder in your project for it work properly.

Adding on to this answer, the Media URL/Root and Static URL/Root collectively help Django process images for your application.
When you add the default image in models.py, make sure to put '/static/image.jpg' and once you're rending in the template load static with {% load static %}.

Related

django models imagefield upload_to method not working

I am using create view to create a model instance (product).
Evey thing is working fine bt after doing some new migrations
i can't get the uploaded image, instead getting default image.
I think upload_to method of models isn't working.
i also used this in my urls
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is my settigs vars:
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
This is my models.py:
class Product(models.Model):
TYPE = [
('Sell','Sell'),
('Rent','Rent'),
('Sell or Rent','Sell or Rent'),
]
owner = models.ForeignKey(Owner, on_delete=models.CASCADE)
title = models.CharField(max_length = 25)
type = models.CharField(max_length = 12, choices = TYPE, default = 'Sell')
price = models.IntegerField()
description = models.TextField(default="No Description Given")
image = models.ImageField(default='default.jpeg', upload_to='product')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('store')
and this is my views.py:
class ProductCreateView(LoginRequiredMixin, CreateView):
model = Product
fields = ['title','type', 'price','description', 'image']
def form_valid(self, form):
print(self.request.POST)
owner , created = Owner.objects.get_or_create(user=self.request.user)
form.instance.owner = self.request.user.owner
return super().form_valid(form)
I am getting default image for every new product created.
Thanks
P.S. when i am adding product from admin panel then every thing is working fine.

How to include rows of data in a single django model entry?

I am working on multiple django sites and have been limited in making my project look nice for clients.
For example in the same app I have two models images and image galleries. It would be so much nicer to just have an admin entry for galleries and in that a table of images.
That's exactly what InlineModelAdmin is for. Taken a models.py like this:
class Gallery(models.Model):
name = models.CharField(max_length=100)
class Image(models.Model):
image = models.ImageField()
gallery = models.ForeignKey(Gallery)
You create an admin.py like this and only register an admin class for the Gallery:
class ImageInline(admin.TabularInline):
model = Image
class GalleryAdmin(admin.ModelAdmin):
inlines = [ImageInline]
admin.site.register(Gallery, GalleryAdmin)
This is my solution thanks to Dirk's help.
from django.db import models
PHOTO_PATH = 'media_gallery'
class Gallerys(models.Model):
title = models.CharField(max_length=30, help_text='Title of the image maximum 30 characters.')
slug = models.SlugField(unique_for_date='date', help_text='This is automatic, used in the URL.')
date = models.DateTimeField()
class Meta:
verbose_name_plural = "Image Galleries"
ordering = ('-date',)
def __unicode__(self):
return self.title
class Images(models.Model):
title = models.CharField(max_length=30, help_text='Title of the image maximum 30 characters.')
content = models.FileField(upload_to=PHOTO_PATH,blank=False, help_text='Ensure the image size is small and it\'s aspect ratio is 16:9.')
gallery = models.ForeignKey(Gallerys)
date = models.DateTimeField()
class Meta:
verbose_name_plural = "Images"
ordering = ('-date',)
def __unicode__(self):
return self.title
import models
from django.contrib import admin
class ImageInline(admin.TabularInline):
model = Images
class GallerysAdmin(admin.ModelAdmin):
list_display = ('title', 'date', 'slug')
inlines = [ImageInline]
admin.site.register(models.Gallerys,GallerysAdmin)

Why is my image upload failing in django?

I am trying to build a django app and host it on webfaction.
My model looks like this:
class Post(models.Model):
title = models.CharField(max_length=512)
image = models.ImageField(upload_to='blogImages/')
body = models.TextField()
visible = models.BooleanField()
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField('Tag', null=True, blank=True)
def __unicode__(self):
return self.title
The settings look like this:
MEDIA_ROOT = '/home/myself/webapps/dev_static/media/'
MEDIA_URL = 'http://dev.example.com/static/media/'
STATIC_ROOT = '/home/myself/webapps/dev_static/'
STATIC_URL = 'http://dev.example.com/static/'
When I go to my server and try to upload an image, I get this error:
SuspiciousOperation at /admin/blog/post/add/
Attempted access to '/home/myself/wrong/path/appname/blogImages/Portal2-Logo.jpg' denied.
I'm trying to figure out where the wrong path could come from. Where else should I look for the wrong path?
i have had the same problem, solved with
image = models.ImageField(upload_to='/blogImages/')
instead of (upload_to='blogImages/')
The error is returning the old static media path. It started working correctly using the the correct path after I restarted Apache.

Not able to diplay images in django

Im trying to make a shopping portal with a recommendation system
Not able to display images in the templates...
The HTML pages when opened without running the server opens them though
tried setting the MEDIA_URL and MEDIA_ROOT
settings as given:
MEDIA_ROOT = "/home/jose/Estore/estore/images/"
MEDIA_URL = '/images/'
The Model I defined is as given:
#Model for Books
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
section = models.CharField(max_length=50)
authors = models.CharField(max_length=150)
subject = models.CharField(max_length=50)
publisher = models.CharField(max_length=50)
publication_date = models.DateField(blank=True, null=True)
price = models.DecimalField(max_digits=6,decimal_places=2)
photo = models.ImageField(upload_to='product_photo/books/',blank=True)
description = models.TextField()
rating = models.DecimalField(max_digits=2,decimal_places=1)
def __str__(self):
return self.title
Have you set your urlconf?
http://docs.djangoproject.com/en/dev/howto/static-files/#serving-other-directories
here is how to do that. You need to set this in order for static serving to work.
Did this help?

Integrating Photologue

I want to integrate photologue with my Django app and use it to display photos in a vehicle inventory...kinda like what is offered by Boost Motor Group Inc. I've already integrated the app so the next step which I'm trying to figure out is how to hook it up into my vehicle model and also how to display the photos. My vehicle model looks like this BTW
class Vehicle(models.Model):
stock_number = models.CharField(max_length=6, blank=False)
vin = models.CharField(max_length=17, blank=False)
common_vehicle = models.ForeignKey(CommonVehicle)
exterior_colour = models.ForeignKey(ExteriorColour)
interior_colour = models.ForeignKey(InteriorColour)
interior_type = models.ForeignKey(InteriorType)
odometer_unit = models.ForeignKey(OdometerUnit)
status = models.ForeignKey(Status)
odometer_reading = models.PositiveIntegerField()
selling_price = models.PositiveIntegerField()
purchase_date = models.DateField()
sales_description = models.CharField(max_length=60, blank=False)
feature_sets = models.ManyToManyField(FeatureSet, blank=True)
features = models.ManyToManyField(Feature, blank=True)
def __unicode__(self):
return self.stock_number
For your purposes I would recommend you check out django-imagekit (I wrote both imagekit and photologue). It was designed to be integrated into other applications as opposed to being a stand-alone application itself. After that, as Dominic said, we'll need to know more about your requirements.
I use ImageKit (great!)
model.py
from imagekit.models import ImageModel
class Photo(ImageModel):
name = models.CharField(max_length=100)
original_image = models.ImageField(upload_to='photos')
num_views = models.PositiveIntegerField(editable=False, default=0)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
class IKOptions:
# This inner class is where we define the ImageKit options for the model
spec_module = 'cms.specs'
cache_dir = 'photos'
image_field = 'original_image'
save_count_as = 'num_views'
class Vehicle(models.Model):
images = generic.GenericRelation('Photo', blank = True, null = True)
specs.py
from imagekit.specs import ImageSpec
from imagekit import processors
from imagekit.lib import *
# first we define our thumbnail resize processor
class ResizeThumb(processors.Resize):
width = 100
height = 75
crop = True
# now lets create an adjustment processor to enhance the image at small sizes
class EnchanceThumb(processors.Adjustment):
contrast = 1.2
sharpness = 1.1
# now we can define our thumbnail spec
class Thumbnail(ImageSpec):
processors = [ResizeThumb, EnchanceThumb]
in your template you will access this thumbnails like this:
{% for p in vehicle.images.all %}
{{ p.get_thumbnail.url }}
{% endfor %}
admin.py could look like this:
class ImagesInline(generic.GenericTabularInline):
model = Photo
max_num =4
class VehicleAdmin(admin.ModelAdmin):
inlines = [ImagesInline]
All about ImageKit
add the file specs.py to your app and tell ImageKit of it like this
class IKOptions:
# This inner class is where we define the ImageKit options for the model
spec_module = 'cms.specs # ur_app.specs
add a field to your Photo-Model to save what kind of view/ content it shows. i.e. ChoiceField
In view/template you can filter for it