How do I include image files in Django templates?

前端 未结 11 1695
时光说笑
时光说笑 2020-11-27 10:35

I\'m new to Django and I\'m trying to learn it through a simple project I\'m developing called \'dubliners\' and an app called \'book\'. The directory structure is like this

11条回答
  •  心在旅途
    2020-11-27 11:15

    I have spent two solid days working on this so I just thought I'd share my solution as well. As of 26/11/10 the current branch is 1.2.X so that means you'll have to have the following in you settings.py:

    MEDIA_ROOT = "" (i.e. /home/project/django/app/templates/static)
    MEDIA_URL = "http://localhost:8000/static/"
    

    *(remember that MEDIA_ROOT is where the files are and MEDIA_URL is a constant that you use in your templates.)*

    Then in you url.py place the following:

    import settings
    
    # stuff
    
    (r'^static/(?P.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
    

    Then in your html you can use:

    
    

    The way django works (as far as I can figure is:

    1. In the html file it replaces MEDIA_URL with the MEDIA_URL path found in setting.py
    2. It looks in url.py to find any matches for the MEDIA_URL and then if it finds a match (like r'^static/(?P.)$'* relates to http://localhost:8000/static/) it searches for the file in the MEDIA_ROOT and then loads it

提交回复
热议问题