How do I include image files in Django templates?

前端 未结 11 1641
时光说笑
时光说笑 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 10:51

    I tried various method it didn't work.But this worked.Hope it will work for you as well. The file/directory must be at this locations:

    projec/your_app/templates project/your_app/static

    settings.py

    import os    
    PROJECT_DIR = os.path.realpath(os.path.dirname(_____file_____))
    STATIC_ROOT = '/your_path/static/'
    

    example:

    STATIC_ROOT = '/home/project_name/your_app/static/'    
    STATIC_URL = '/static/'    
    STATICFILES_DIRS =(     
    PROJECT_DIR+'/static',    
    ##//don.t forget comma    
    )
    TEMPLATE_DIRS = (    
     PROJECT_DIR+'/templates/',    
    )
    

    proj/app/templates/filename.html

    inside body

    {% load staticfiles %}
    
    //for image
    
    img src="{% static "fb.png" %}" alt="image here"
    
    //note that fb.png is at /home/project/app/static/fb.png
    

    If fb.png was inside /home/project/app/static/image/fb.png then

    img src="{% static "images/fb.png" %}" alt="image here" 
    

提交回复
热议问题