Search code examples
pythondjangodjango-templatesdjango-file-upload

django templates upload file - how to handle a non-existant physical file


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?


Solution

  • 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' }}" />