Images from ImageField in Django don't load in template

后端 未结 7 1390
温柔的废话
温柔的废话 2020-12-08 15:58

I\'m building a gallery using Django(1.5.1) on my local machine. In my Album model I have a ImageField. There is a view to show all images of an album. It works

相关标签:
7条回答
  • 2020-12-08 16:37

    Well I know this question is old but I solved it right now after prove all options:

    1. settings.py:
        MEDIA_URL = '/media/'
        MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    
    1. urls.py DANGER!!! Here one of my errors was that I used my_app/urls.py... If you want to use my_app/urls.py you need to add "/namespace_name{{ image.image.url }}" to img' src:
        from django.conf.urls.static import static
        from django.contrib.staticfiles.urls import staticfiles_urlpatterns
        from django.conf import settings
    
        urlpatterns += staticfiles_urlpatterns()
        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
    1. Your template, detail.html
        img src="{{ image.image.url }}" alt="{{ image.title }}"
    

    NOTES: Yo don't need MEDIA_URL, be careful with the '/' because image.image.url is absolute, so if you use a namespace then you don't need to add the finish slash.

        img src="/namespace_name/{{ image.image.url }}"  --> BAD!!!
        img src="/namescape_name{{ image.image.url }}"   --> GOOD!!!
    
    0 讨论(0)
提交回复
热议问题