Django MEDIA_URL and MEDIA_ROOT

305,734

Solution 1

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

Solution 2

Please read the official Django DOC carefully and you will find the most fit answer.

The best and easist way to solve this is like below.

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)

Solution 3

For Django 1.9, you need to add the following code as per the documentation :

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

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

For more info, you can refer here : https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-files-uploaded-by-a-user-during-development

Solution 4

Here What i did in Django 2.0. Set First MEDIA_ROOT an MEDIA_URL in setting.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'data/') # 'data' is my media folder
MEDIA_URL = '/media/'

Then Enable the media context_processors in TEMPLATE_CONTEXT_PROCESSORS by adding

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            #here add your context Processors
            'django.template.context_processors.media',
        ],
    },
},
]

Your media context processor is enabled, Now every RequestContext will contain a variable MEDIA_URL.

Now you can access this in your template_name.html

<p><img src="{{ MEDIA_URL }}/image_001.jpeg"/></p>

Solution 5

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

Yes. For development, it's as easy as adding this to your URLconf:

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

However, for production, you'll want to serve the media using Apache, lighttpd, nginx, or your preferred web server.

Share:
305,734

Related videos on Youtube

Dan
Author by

Dan

Updated on May 03, 2022

Comments

  • Dan
    Dan almost 2 years

    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.

  • Micah Carrick
    Micah Carrick about 13 years
    PS. You can then use this in your templates: <img src="{{ MEDIA_URL }}images/myimage.png"/>
  • Jack Zhang
    Jack Zhang over 10 years
    I don't think it's good to add ^ sign before media//(?P<path>.*)$, sometime when we access media file in app url path (like http://127.0.0.1:8000/myapp/media/img/logo.png), this regular won't math.
  • codeVerine
    codeVerine over 10 years
    It is a new feature added in django 1.5
  • tambalolo
    tambalolo over 10 years
    I've been struggling for 2 days now why my images return 404. This is the only thing I'm missing and I can't find it in Django doc. Thanks.
  • andilabs
    andilabs about 10 years
    is it ok to use it this way in production with apache?
  • Vikas Gulati
    Vikas Gulati about 10 years
    @andi - No its not okay to use it this way in production. It should be configured via apache on your production.
  • ErDmKo
    ErDmKo over 9 years
  • jozxyqk
    jozxyqk over 8 years
    But it's OK to leave this code here in production with no if settings.DEV check because it's disabled automatically?
  • unixeo
    unixeo over 8 years
    This is the solution for django >1.9, thnks.
  • Thane Brimhall
    Thane Brimhall about 8 years
    If you're using Django 1.5+, please see the answer below; it is a better solution.
  • Jarno
    Jarno almost 8 years
    Just make sure to put this into the urls.py of your project and not of your app, what I accidentally did.
  • CoderGuy123
    CoderGuy123 over 7 years
    Does not work for me (1.10). TypeError: view must be a callable or a list/tuple in the case of include()..
  • CoderGuy123
    CoderGuy123 over 7 years
    Worked for me on 1.10 too.
  • Menachem Hornbacher
    Menachem Hornbacher almost 7 years
    What does that mean how do you configure the server?
  • HBat
    HBat almost 7 years
    Just to follow up @jozxyqk 's comment, I understand that there is no need to use if settings.DEBUG: as the answer below, if the code will be used in production?
  • Fusion
    Fusion almost 7 years
    does not work for me. Perhaps there are any necesary underlying settings in settings.py?
  • user7804781
    user7804781 about 6 years
    I get an unresolved reference to "patterns", is that imported from somewhere?
  • user7804781
    user7804781 about 6 years
    is this in your app or project urls.py?
  • Eje
    Eje almost 6 years
    For Django 2.0.*, check out the docs here.
  • David Maness
    David Maness over 4 years
    wonderfully explained -- this was the answer for me. The key was adding the media context processor.
  • daka
    daka about 4 years
    Will this work outside debug mode? If not, do you know how it can be made to work? I plan to run the app locally only.
  • daka
    daka about 4 years
    Ok, to answer my own question, see the following two answers. one and two.
  • artu-hnrq
    artu-hnrq about 3 years
    very nice context_processors tip
  • Sumit Kumar Gupta
    Sumit Kumar Gupta over 2 years
    This is better option but 'django.template.context_processors.media' worked for me