Display an image located in the database in Django

前端 未结 3 598
失恋的感觉
失恋的感觉 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:30

    You need to use {{MEDIA_URL}} or {{STATIC_URL}} , the choice depends on how you manage your files on server.

    0 讨论(0)
  • 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 -

    <img src="{{ image.model_pic.url }}">
    

    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.

    0 讨论(0)
  • 2021-02-09 10:39

    Try doing the following:

    from django.conf import settings
    from django.conf.urls.static import static
    from . import views
    
    urlpatterns = [
                .....
    ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
    
    0 讨论(0)
提交回复
热议问题