简体   繁体   中英

Django Media Files on Development Server

I have the following URL patterns set up on my development server. DEBUG = True. The link to images on my media directory does not work (ie localhost/media/images/img1.jpg does not load image). However, it works if I insert the media url pattern in front of the portion commented MAIN URL PATTERNS, which shows that my media links are set up correctly. What is going on here?

urlpatterns = patterns("",
   # works if I insert the media url pattern here
   # MAIN URL PATTERNS
   (r"^admin/"                            , include(admin.site.urls)),
   (r"^group/(?P<dpk>\d+)/(?P<show>\S+)/" , GroupView.as_view(), {}, "group"),
   (r"^group/(?P<dpk>\d+)/"               , GroupView.as_view(), {}, "group"),
   (r"^add-images/(?P<dpk>\d+)/"          , AddImages.as_view(), {}, "add_images"),
   (r"^slideshow/(?P<dpk>\d+)/"           , SlideshowView.as_view(), {}, "slideshow"),
   (r"^image/(?P<mfpk>\d+)/"              , ImageView.as_view(), {}, "image"),
   (r"^image/"                            , ImageView.as_view(), {}, "image"),
   (r""                                   , Main.as_view(), {}, "photo"),
   # END OF MAIN URL PATTERNS
) 

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

The correct way to do this would be:

if settings.DEBUG:
    urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + urlpatterns

(This removes the hard-coded MEDIA_URL, too)

Your photo view is capturing everything, because you didn't put any start/end modifiers on the pattern. The last two patterns should be:

(r"^image/$", ...
(r"^$", ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM