TLT: Determining, In a Django Template, Whether a User Uploaded an Image

For some reason, managing file uploads in Django isn't the easiest thing to do. Well, not for some reason, but for a few reasons. If that weren't the case, people wouldn't have created so many file management packages for the framework.

Images fall under the file management umbrella, at least in the following situation.


I have a model containing an ImageField attribute. Creation of subsequent database objects does not require population of this field. In other words, the user doesn't need to populate the ImageField before submitting data via a related form. The form, for the record, reflects this notion.

The problem is that when a user doesn't upload an image, checking whether a user uploaded an image in the template isn't as straightforward as checking the ImageField attribute for None in the template. It'll always return something. We want to check to see if the path string is empty.


To solve our problem, we check the ImageField attribute for an empty string.


class Book(models.model):  
    cover_image = models.ImageField(upload_to="images/", default="")

class BookForm(forms.ModelForm):  
    cover_image = forms.ImageField(required=False)


{% if my_book_context_object.cover_image != "" %}
<img src="my/image/exists/"></img>  
{% else %}
<img src="my/image/doesnt/exist/"></img>  
{% endif %}

This may be a pretty bad way to go about it. Might be much better to add a boolean model method like has_image() that just returns True if the image path isn't empty. That would keep most of the logic operations in the model class, rather than add more complexity to the code by keeping some of that logic in the template.

I'm actually looking for a better way to do this. I created a post on SO and have yet to receive a response. That post is here.


Software Engineer

Subscribe to GregBlogs