Django MEDIA_URL and MEDIA_ROOT

前端 未结 13 1225
天命终不由人
天命终不由人 2020-11-22 11:36

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

13条回答
  •  抹茶落季
    2020-11-22 12:14

    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.*)$', '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

提交回复
热议问题