Answer the question
In order to leave comments, you need to log in
Django ImageField displaying an image, what's wrong?
Hello. Actually a problem. I did everything according to examples and in different ways, I found similar questions here, but somehow they didn’t help me much. I want to display in a given model a lot of pictures (if necessary) and the main cover. When viewing on my page in one way or another, just the path to the file is written, but there is no picture itself (404 in the console), as well as on the admin panel. The images themselves are all as expected in the folders.
settings:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
],
},
},
]
class Books(models.Model):
name = models.CharField(max_length=120)
date = models.DateField(null=True,blank=True)
EAN = models.IntegerField(null=True,blank=True)
description = models.TextField(max_length=500,null=True,blank=True)
list_char = models.TextField(max_length=200,null=True,blank=True)
img = models.ImageField(upload_to="fstimg/",null=True, blank=True)
def __str__(self):
return self.name
class ImageBooks(models.Model):
imagebooks = models.ForeignKey(Books,blank=True,null=True,default=None,related_name='images')
image = models.ImageField(upload_to='images/',null=True, blank=True)
def book(request):
all_books = Books.objects.all()
context = {"book_objects" : all_books,}
return render(request, "book.html", context)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^book/$', book),
#url(r'^book/$', BooksView.as_view()),
url(r'^$', home, name='home'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_ROOT, document_root=settings.MEDIA_ROOT)
{% for obj in book_objects %}
<ul>
<h1>{{ obj }}</h1>
{% for i in obj.images.all %}
{{ i.image.url }}
<img src="{{ i.image.url }}" />
{% endfor %}
{{ obj.img.url }}
<li><img src="{{ obj.img.url }}" alt=""></li>
<li>Date: {{ obj.date }}</li>
<li>EAN: {{ obj.EAN }}</li>
<li>Description: {{ obj.description }}</li>
<li>List Heroes: {{ obj.list_char }}</li>
</ul>
{% endfor %}
Answer the question
In order to leave comments, you need to log in
You have a typo in the line where you add media file urls, here is the corrected one, compare:
..
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
..
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question