Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default image for ImageField in Django's ORM

I'm using an ImageField to store profile pictures on my model.

How do I set it to return a default image if no image is defined?

like image 744
Yuvi Avatar asked Aug 14 '09 09:08

Yuvi


People also ask

What is default in Django model?

default: The default value for the field. This can be a value or a callable object, in which case the object will be called every time a new record is created. null: If True , Django will store blank values as NULL in the database for fields where this is appropriate (a CharField will instead store an empty string).

What is image field in Django?

ImageField in Django Forms is a input field for upload of image files. The default widget for this input is ClearableFileInput. It normalizes to: An UploadedFile object that wraps the file content and file name into a single object.


2 Answers

I haven't tried this, but I'm relatively sure you can just set it as a default in your field.

pic = models.ImageField(upload_to='blah', default='path/to/my/default/image.jpg') 

EDIT: Stupid StackOverflow won't let me comment on other people's answers, but that old snippet is not what you want. I highly recommend django-imagekit because it does tons of great image resizing and manipulation stuff very easily and cleanly.

like image 175
ericflo Avatar answered Oct 17 '22 04:10

ericflo


In models.py

image = models.ImageField(upload_to='profile_pic', default='default.jpg') 

In settings.py add this:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' 

Now, Manually, add an image with a name ''default' into the media folder.

like image 37
Manish Avatar answered Oct 17 '22 02:10

Manish