-->

django 1.10 media images don't show

2019-04-12 04:42发布

问题:

I have had django media images working in an existing django 1.7 project by adding the following to site urls.py:

urlpatterns = patters(
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)

This url structure doesn't work in django 1.10 and so I changed it to the reccommended here Django MEDIA_URL and MEDIA_ROOT:

urlpatterns = [

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

This fails to render any uploaded media images. Is there an equivalent media url patter for django 1.10 I can use?

回答1:

You can use this: (Django docs 1.10 Serving files uploaded by a user during development)

urlpatterns = [
   ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

OR you can use this (if you only want it in development with the Debug = True in you'r settings): Django docs 1.10 Serving files in development

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

For me the {{ MEDIA_URL }} didn't work anymore in my template file, I used the {% get_media_prefix %}:

Ex.:

<img src="{% get_media_prefix %}{{ product.image }}">