54👍
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.
19👍
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.
- [Django]-Best practice for Django project working directory structure
- [Django]-What does this Django regular expression mean? `?P`
- [Django]-How to TRUNCATE TABLE using Django's ORM?
11👍
You could theoretically also use a function within your model definition. But I dont know whether this is good practice:
class Image(model.Models):
image = ....
def getImage(self):
if not self.image:
# depending on your template
return default_path or default_image_object
and then within a template
<img src="img.getImage" />
This gives you a great deal of flexibility for the future…
I’m using sorl for thumbnails generation with great success
- [Django]-How do I match the question mark character in a Django URL?
- [Django]-Save base64 image in django file field
- [Django]-Naming convention for Django URL, templates, models and views
7👍
In your image field
field = models.ImageField(upload_to='xyz',default='default.jpg')
Note : path should be inside MEDIA_ROOT.
- [Django]-Execute code when Django starts ONCE only?
- [Django]-Additional field while serializing django rest framework
- [Django]-Can I use Socket.IO with Django?
3👍
you could try this in your template:
{% ifequal object.image None %}
<img src="DEFAULT_IMAGE" />
{% else %}
display image
{% endifequal %}
- [Django]-Additional field while serializing django rest framework
- [Django]-Django edit user profile
- [Django]-Making django server accessible in LAN
0👍
You can provide an initial value with the ‘default’ parameter.
If there is already an image and you want to set it to default (instead of deleting it), you can try something like this:
DEFAULT = 'img/default.jpg'
class Example(models.Model):
image = models.ImageField(default=DEFAULT)
def set_image_to_default(self):
self.image.delete(save=False) # delete old image file
self.image = DEFAULT
self.save()
Then you can use set_image_to_default()
instead of image.delete()
, if you prefer the default.
- [Django]-What is the difference between null=True and blank=True in Django?
- [Django]-Unable to perform collectstatic
- [Django]-What is the equivalent of "none" in django templates?