I am trying to display uploaded images to a template for my imaginary vegetable catalogue.
I have a page to add a new vegetable and upload images. The main template is a list of vegetables which will later have thumbnails.
Now, when viewing the detail page of the vegetable I want to display its images, but the template is only displaying the string 'VegetableImage Object' in place of an image, even with img tags.
I am confused because the template has obviously found the images but they are displayed just as a generic string.
models.py
class Vegetable(models.Model):
title = models.CharField(max_length=0)
category = models.CharField(max_length=50,
choices=CATEGORY_CHOICES)
thumbnail = models.ImageField(upload_to = 'uploaded_images/')
class VegetableImage(models.Model):
vegetable = models.ForeignKey(Vegetable, default=None, related_name='images')
image = models.ImageField(upload_to='images/vegetable',
verbose_name='image',)
view for main template (a list of all vegetables) and detail view
class VegetableView(generic.ListView):
template_name = 'vegetable/vegetable.html'
context_object_name = 'vegetable_list'
def get_queryset(self):
return Vegetable.objects.all()
class DetailView(generic.DetailView):
model = Vegetable
template_name = 'vegetable/detail.html'
Detail template for displaying detail of vegetable
{% if view %}
<h1>Title: {{ vegetable.title }}</h1>
<h2>Category: {{ vegetable.category }}</h2>
<p>Thumbnail: {{ vegetable.thumbnail }}</p>
<p>Images:
{% for vegetable in vegetable.images.all %}
{{ vegetable }}
{% endfor %}
</p>
{% else %}
<p> no vegetables found - error </p>
{% endif %}
Try to display the image using the following code in your template:
<img src="{{ vegetable.image.url }}" alt="...">
This is how you access the url from the imagefield object.
In more technical detail, ImageField
inherits from FileField
. As it is stated in the documentation:
When you access a
FileField
on a model, you are given an instance ofFieldFile
as a proxy for accessing the underlying file...
Therefore:
A read-only property to access the file’s relative URL by calling the
url()
method of the underlying Storage class.
To display uploaded user files in development you need to change the urls.