3

I am using django to upload an image file to the server.

When the user attempts to view a missing image in the django templates, there is just the broken image displayed, but I want to display a default missing image file.

How do I handle the possibility of the physical file being deleted (or just missing) but the location still stored in the database?

user3354539
  • 1,245
  • 5
  • 21
  • 40

2 Answers2

2

Use the exists() method of the file storage. For example if the name of the image field is image the code will look like:

if obj.image.storage.exists(obj.image.name):
    ...

To simplify things you can create a custom template filter:

from django.conf import settings

@register.filter
def default_image(image, default_file):
    if image.storage.exists(image.name):
        return image.url
    return settings.STATIC_URL + default_file

And then use it right in the template:

<img src="{{ obj.image|default_image:'no-image.png' }}" />
catavaran
  • 44,703
  • 8
  • 98
  • 85
  • catavaran, I am getting the error message `'str' object has no attribute 'storage'`. What import statement must I include in the filter file? Also, I changed `@register.simple_tag` to `@register.filter()`. Am I on the right track? – user3354539 Feb 24 '15 at 05:18
  • Sorry, of course it should be the `@reguster.filter`. As for the `'str' object...` error I suspect you pass the wrong attribute to the filter. Show the template fragment where you got this error, please. – catavaran Feb 24 '15 at 05:32
  • Just to be sure: you should pass the image or file object to the template filter, but not the filename. – catavaran Feb 24 '15 at 05:57
  • Actually I have been having issues with the template code because the **{{STATIC_URL}}** variable inside the template variable (I am not sure how to structure it) as shown here: `` – user3354539 Feb 24 '15 at 06:22
  • Remove the `url` part of the variable and add the `STATIC_URL` in the template filter like in my example: `{{ attachment_detail.attachment_document|default_image:'img/attachments/attachment_not_uploaded.png' }}` – catavaran Feb 24 '15 at 06:31
0

Check the file object using python

file_obj = Model.objects.get(id=1)

if os.path.exists(file_obj.file):
    file_path = file_obj.file
else:
    file_path = default_path
Raja Simon
  • 10,126
  • 5
  • 43
  • 74