Display an image located in the database in Django

前端 未结 3 597
失恋的感觉
失恋的感觉 2021-02-09 09:56

I just want to display an image that i have uploaded through the admin module, through an html image tag on a web page. The image is located in /home/user/work/djcode/media/chic

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-09 10:37

    Your use of the url function on the image field in your template is not quite correct - {{ image.model_pic.url }} should fix the issue. You just need to drop the {{ MEDIA_URL }} bit.

    Your html should be -

    
    

    Have a look at the documentation on using files in models.

    If you're still having trouble then it may be an issue with serving static files. Serving static files in django varies depending on whether you're doing it in production or just using the python manage.py runserver command.

    To server media files during development (with python manage.py runserver), make sure you've got your MEDIA_URL and MEDIA_ROOT correct in your settings.py then you can append the following to your url conf -

    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)
    

    Have a look at the docs for instructions on how to serve files in production.

提交回复
热议问题