1

I am ashamed to ask a question of that sort but I still can not solve my problem. I normally uploaded image in my media directory and can see image link in my admin but if I click on link I get:

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/photo/img/9.jpg Using the URLconf defined in TeamStudy.urls, Django tried these URL patterns, in this order: ^admin/ The current URL, photo/img/9.jpg, didn't match any of these. my project structure:

src
static/
      photo/ 
           img/

settings:

PROJECT_DIR = os.path.dirname(os.path.dirname(__file__))
BASE_DIR = os.path.dirname(PROJECT_DIR)

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

urls.py

urlpatterns = [
   url(r'^admin/', include(admin.site.urls)),
]

I suspect it perhaps quite simple and I miss something. Please point me.

Andriy
  • 311
  • 1
  • 7
  • 19
  • 1
    why do you keep MEDIA_ROOT inside STATIC_ROOT ? when you can create another directory named 'media', at the same level as 'static' directory? – Amrullah Zunzunia Jun 22 '16 at 11:38

3 Answers3

3

You need to add the media MEDIA_ROOT and MEDIA_URL in your urlpatterns

urlpatterns = [
   url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

check following links for more details

Accessing "Media" files in Django

Django classifies user files in two types

  1. Static files
  2. Media files

this link helps you understand the difference between them

Your issues deals with Media files.

In future development, you may need to serve static files, to serve them you will need to add STATIC_ROOT and STATIC_URL to the urlpatterns in a similar way that MEDIA_ROOT and MEDIA_URL are added

Anuj
  • 994
  • 11
  • 21
  • Welcome :) Next time before you post such a question make sure you google properly! – Anuj Jun 22 '16 at 12:07
0

Change your URL's patterns:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
   url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

for more info Django Docs

Ravi Kumar
  • 1,769
  • 2
  • 21
  • 31
0

First point: don't put uploaded medias in you static directory - static is for static files that are part of your project (css, js etc) -, you want to use MEDIA_ROOT and MEDIA_URL for this.

wrt/ serving the static and media contents, it depends on the environment. On your local dev environment you want to use the staticfile.views to serve both static and medias as mentionned in the other answers, but don't do this in production : on a production server, you want to use your front web server to serve static (and media) contents.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118