Default image for ImageField in Django's ORM

大城市里の小女人 提交于 2019-11-26 16:33:19

问题


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?


回答1:


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.




回答2:


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




回答3:


you could try this in your view:

{% ifequal object.image None %}
    <img src="DEFAULT_IMAGE" />
{% else %}
    display image
{% endifequal %}



回答4:


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.




回答5:


In your image field

field = models.ImageField(upload_to='xyz',default='default.jpg')

Note : path should be inside MEDIA_ROOT.




回答6:


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.



来源:https://stackoverflow.com/questions/1276887/default-image-for-imagefield-in-djangos-orm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!