Serving static media during Django development: Why not MEDIA_ROOT?

前端 未结 3 1336
不知归路
不知归路 2020-12-08 15:35

I read this guide about serving static media with Django during development.

I noticed that MEDIA_URL and MEDIA_ROOT were not used in this.

3条回答
  •  萌比男神i
    2020-12-08 15:54

    Straight from the comments in settings.py...

    MEDIA_ROOT

    The MEDIA_ROOT is the absolute path to the directory that holds media such as /home/media/media.lawrence.com/.

    MEDIA_URL

    The MEDIA_URL is the URL that handles the media served from MEDIA_ROOT. Make sure to use a trailing slash if there is a path component (optional in other cases). Examples: "http://media.lawrence.com", "http://example.com/media/".

    So, to reword those... The MEDIA_ROOT is where the files live physically on your system, and the MEDIA_URL is where those files are mapped to. In development, this might not always be accessible, and in most cases your dev environment and your production environment are not the same, and it is something you're going to have to go back and change. The other thing is that it is NOT A GOOD PRACTICE when Django was designed NOT to serve static content for you.

    If you're going to use this in development, I suggest you use the method of limiting it to DEBUG=True. Telling Django to serve static content from a temporary location while in development when the DEBUG is set to True is a much better and safer practice. You're NOT going to put your site into production with DEBUG on, right? Well, at least you shouldn't.

    Here is how I implemented it:

    settings.py:

    STATIC_DOC_ROOT = os.path.join(os.getcwd(), 'site_media')
    

    urls.py:

    from django.conf import settings
    ## debug stuff to serve static media
    if settings.DEBUG:
        urlpatterns += patterns('',
            (r'^site_media/(?P.*)$', 'django.views.static.serve', 
                {'document_root': settings.STATIC_DOC_ROOT}),
       )
    

    This way any project I'm working on has a site_media directory inside of it with all of the media necessary. In dev it is self-contained and I don't have to flip any bits in the settings except for DEBUG, which I would be doing anyways.

提交回复
热议问题