Good afternoon, I try to make a website on Django, I want to bring cases to the main page with their previews, but the Django test server answers 404 errors every time. Django 1.9

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 

settings.py

 STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media/') MEDIA_URL = '/static/media/' 

urls.py (which is in the project directory, not the application)

 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) 

views.py

 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() 

index.html

  {% 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 %} 

I rummaged through all the forums and documentation on Django, but did not find a solution.

  • What url is generated in img src? - Chikiro
  • The picture really lies in BASE_DIR / static / media / images / 2.jpg? Is BASE_DIR set correctly? - Flowneee
  • BASE_DIR looks like this: BASE_DIR = os.path.dirname (os.path.dirname (os.path.abspath ( file ))) - oskin1
  • The static folder is in the root of the directory, next to the application and project folder, manage.py and so on. - oskin1 pm

1 answer 1

Finally, I found a solution to the problem - do not use the media folder attachment in static

It was like this:

 STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media/') MEDIA_URL = '/static/media/' 

And it is necessary so:

 STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/'