Answer the question
In order to leave comments, you need to log in
How to display images in a template?
Good afternoon, I'm trying to make a site on Django, I want to display cases with their previews on the main page, but the Django test server responds with a 404 error every time. (Django 1.9)
I've searched through all the Django forums and documentation, but still haven't found a solution.
The following URL is escaped in the browser: 127.0.0.1:8000/static/media/images/2.jpg
BASE_DIR looks like this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))
The static folder is at the root of the directory, next to the application and project folders, manage.py and so on
models.py
from django.db import models
class Case(models.Model):
case_name = models.CharField(max_length=30)
case_preview = models.ImageField(upload_to='images')
def __str__(self):
return self.case_name
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media/')
MEDIA_URL = '/static/media/'
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
urlpatterns = patterns('',
url(r'^landing/', include('landing.urls', namespace="landing")),
url(r'^admin/', admin.site.urls),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.shortcuts import get_object_or_404, render
from django.views import generic
from .models import Case
class IndexView(generic.ListView):
template_name = 'landing/index.html'
context_object_name = 'case_list'
def get_queryset(self):
return Case.objects.all()
{% if case_list %}
<ul>
{% for case in case_list %}
<img src="{{ MEDIA_URL }}{{ case.case_preview.url }}"/>
<li>{{ case.case_name }}</li>
{% endfor %}
</ul>
{% else %}
<p>No cases are available.</p>
{% endif %}
>>> c = Case(case_name="Pic", case_preview="images/2.jpg")
>>> c.save()
>>> c.case_preview
<ImageFieldFile: images/2.jpg>
>>> c.case_preview.path
'C:\\Users\\Oskin\\Desktop\\pyProject\\uni\\static\\media\\images\\2.jpg'
>>> c.case_preview.url
'/static/media/images/2.jpg'
>>>
Answer the question
In order to leave comments, you need to log in
Finally, I found a solution to the problem - not to use the nesting of the media folder in static
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media/')
MEDIA_URL = '/static/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
Add to index.html:
{% load staticfiles %}
img src="{% static "my_app/myexample.jpg" %}"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question