Django MEDIA_URL and MEDIA_ROOT

前端 未结 13 1223
天命终不由人
天命终不由人 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:21

    (at least) for Django 1.8:

    If you use

    if settings.DEBUG:
      urlpatterns.append(url(r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))
    

    as described above, make sure that no "catch all" url pattern, directing to a default view, comes before that in urlpatterns = []. As .append will put the added scheme to the end of the list, it will of course only be tested if no previous url pattern matches. You can avoid that by using something like this where the "catch all" url pattern is added at the very end, independent from the if statement:

    if settings.DEBUG:
        urlpatterns.append(url(r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))
    
    urlpatterns.append(url(r'$', 'views.home', name='home')),
    

提交回复
热议问题