Ahmad AL-Saoud
Ahmad AL-Saoud

Reputation: 23

how to load a img from static folder in python-Django

I try to build a portfolio website using html, css, js and django but i don't know how to load an image from assets in static folder.

This is the template code part:

{% load static%}
...
<div class="col-lg-5 align-items-stretch order-1 order-lg-2 img" 
    style='background-image: url("assets/img/why-us.png");' 
    data-aos="zoom-in" data-aos-delay="150">&nbsp;</div>

Other images get loaded but not this one. Instead I get a Syntax error

Upvotes: 1

Views: 2760

Answers (1)

RaphSinai
RaphSinai

Reputation: 91

Firstly, you need no make sure that the static files are configured correctly in settings.py , check to see if you can find STATIC_URL = 'static/' in your settings.py. If not, add it at the end in a new line.

Then, the next step requires you to create a folder named static , or whatever you defined STATIC_URL to be in settings.py , in the app folder where you wish to use those static files. You will store all your static files in there.

Finally, to use your static files in the template, you need to use the {% static '_FILEPATH_' %} tag, without adding static/ to the pathname.

PS: Make sure to {% load static %} before calling any static files

Ex: If I want to load a stylesheet in my template, my stylesheet will be located in BASEDIR/APPNAME/static/style.css and my <head> would look like this:

<head>
    {% load static %}
    <link rel="stylesheet" src="{% static 'style.css' %}">
</head>

For any other issue try to refer to the Django documentation: How to manage static files - Django Documentation

Upvotes: 1

Related Questions