Solve media directory and URL not found in Django


Un-detected / not found media files folder in Django using development webserver is commonly happen in Django pitfalls.
When configure media directory / folder in Django, you should watch several things to make it loaded properly. Miss-configure of media in Django will lead you into Error media files or not found. So, basically, media folder placed in PROJECT_PATH.

1
2
3
4
5
6
7
PROJECT
  |____ APPS
  |____ STATIC
  |____ MEDIA
  |____ urls.py
  |____ manage.py
  |____ settings.py


So, at this point, we will make media files can be accessed from URL :

1
http://example/media/images/myimage.png

Open “settings.py” :

1
2
3
4
5
6
7
8
9
10
11
import os
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, ‘media’)

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ‘/media/’

Now, did you running development server? You have media folder detected perfectly on Apache ModWSGI but not in development server. Sound familiar? Why this happen? What solution?

Just open your “urls.py” and add this :

1
2
3
4
5
6
7
8
9
10
from django.conf import settings

# … the rest of your URLconf goes here …

if settings.DEBUG:
    urlpatterns += patterns(”,
        url(r’^media/(?P<path>.*)$’, ‘django.views.static.serve’, {
            ‘document_root’: settings.MEDIA_ROOT,
        }),
)

Restart your webserver and you should see media files show up 🙂

PS:
For static files, you can add :

1
2
3
4
5
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

# … the rest of your URLconf goes here …

urlpatterns += staticfiles_urlpatterns()

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.