Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django MEDIA_URL and MEDIA_ROOT

Tags:

django

media

I'm trying to upload an image via the Django admin and then view that image either in a page on the frontend or just via a URL.

Note this is all on my local machine.

My settings are as follows:

MEDIA_ROOT = '/home/dan/mysite/media/'  MEDIA_URL = '/media/' 

I have set the upload_to parameter to 'images' and the file has been correctly uploaded to the directory:

'/home/dan/mysite/media/images/myimage.png' 

However, when I try to access the image at the following URL:

http://127.0.0.1:8000/media/images/myimage.png 

I get a 404 error.

Do I need to setup specific URLconf patters for uploaded media?

Any advice appreciated.

Thanks.

like image 676
Dan Avatar asked Apr 01 '11 19:04

Dan


People also ask

What is MEDIA_URL and Media_root?

The MEDIA_ROOT is the path on the filesystem to the directory containing your static media. The MEDIA_URL is the URL that makes the static media accessible over HTTP.27-Jan-2011.

What is Media_root in Django?

MEDIA_ROOT: The absolute path to the directory where your Django application will serve your media files from.

Where is media root Django?

MEDIA_ROOT: It is the path to the directory in which all the media files will be saved. Here, we have written(BASE_DIR, "media") which means that Django will create a folder named "media" under the base directory and all the media files will be saved in the "media" folder. 3.


1 Answers

UPDATE for Django >= 1.7

Per Django 2.1 documentation: Serving files uploaded by a user during development

from django.conf import settings from django.conf.urls.static import static  urlpatterns = patterns('',     # ... the rest of your URLconf goes here ... ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 

You no longer need if settings.DEBUG as Django will handle ensuring this is only used in Debug mode.


ORIGINAL answer for Django <= 1.6

Try putting this into your urls.py

from django.conf import settings  # ... your normal urlpatterns here  if settings.DEBUG:     # static files (images, css, javascript, etc.)     urlpatterns += patterns('',         (r'^media/(?P<path>.*)$', 'django.views.static.serve', {         'document_root': settings.MEDIA_ROOT})) 

With this you can serve the static media from Django when DEBUG = True (when you run on local computer) but you can let your web server configuration serve static media when you go to production and DEBUG = False

like image 116
Micah Carrick Avatar answered Sep 20 '22 15:09

Micah Carrick