I'm trying to figure out how to solve this problem with the images but I can't find the answer. I'm trying to display an 'ImageField' of my models to a template.
I have uploaded an image through the admin site, and when I want to display it, I can't render the image properly (it appears an icon but can't see the image).
The model I'm trying to show the image from has this statement for the ImageField:
figure = models.ImageField(upload_to='static/img/list-icons',
blank=True,
null=True,
verbose_name=_("Figure"))
Being the 'upload_to' path the path to the static files directory where the images are stored. I'm trying to get the image in the Template with this code (I've tried several combinations):
{% for quiz in quiz_list %}
<tr>
<td>{{ quiz.title }}</td>
<td>{{ quiz.category }}</td>
<td><img src="{{ quiz.figure.url }}" /></td>
<td>{{ quiz.single_attempt }}</td>
</tr>
{% endfor %}
The model is Quiz(ListView) and I've not changed anything from the views.py
(just added recently the images field). Would it be required to add some statements? What kind of?
I've added a mere aproximation of 'MEDIA_ROOT'
in settings.py
, with the path to my static images directory (same as the upload_to in the model), also I'm not sure how to define or if it's necessary to define the 'MEDIA_URL'
.
How could I display images directly from the Model (I also tried {{quiz.figure}}
but just got the 'upload_to' path displayed), picking them from the static directory where they are located? Help would be highly appreciated, thank you. I'll answer to add required aditional info.
EDIT 1: the capture of what it outputs right now is just this:
My urls.py file ends like this:
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
i think it's required to make CSS working properly as it is now.
You are not rendering the image properly.
You should replace
<td><img src="quiz.figure.url" /></td>
with
<td><img src="{{ quiz.figure.url }}" /></td>
UPDATE: It appears that you don't have media url entry in your project urls.py. In the project urls, do this:
from django.conf import settings
from django.conf.urls.static import static
...
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Also, Make sure you have defined appropriate settings in your settings.py
# Media files
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'