Django Global Image File
Add an Image File to the Entire Project
In the previous chapter we learned how to add an image file to an application in a project.
To add images that you can use in the entire project, you simply add them in
a folder on the root of your project.
Just as you did with global .css
files and global
.js
files:
The folder can be called whatever you like, we have already created it, and we called it
mystaticfiles
:
my_tennis_club
manage.py
my_tennis_club/
members/
mystaticfiles/
Add image(s) to the mystaticfiles
folder:
my_tennis_club
manage.py
my_tennis_club/
members/
mystaticfiles/
img_tree.gif
Modify Settings
If you did not do this in the previous chapter, add this STATICFILES_DIRS
list in the settings.py
file:
Add a STATICFILES_DIRS
list:
my_tennis_club/settings.py
:
.
.
STATIC_URL = 'static/'
#Add this in your settings.py file:
STATICFILES_DIRS = [
BASE_DIR / "mystaticfiles"
]
.
.
In the STATICFILES_DIRS
list, you can list all the directories where Django should look for static files.
The BASE_DIR
keyword represents the root directory of the project,
and together with the / "mystaticfiles"
, it
means the mystaticfiles
folder in the root
directory.
Modify the Template
The next step is to include the image in a template:
Open the template.html
template, and add the following:
Example
members/templates/template.html
:
{% load static %}
<!DOCTYPE html>
<html>
<body>
<img src="{% static 'img_tree.gif' %}">
</body>
</html>
Run Example »
Use Images From Both Folders
To use images from different folders, we just add the HTML for the images, and Django will search the folders you have listed until it finds a match:
Example
members/templates/template.html
:
{% load static %}
<!DOCTYPE html>
<html>
<body>
<img src="{% static 'img_tree.gif' %}">
<img src="{% static 'pineapple.jpg' %}">
</body>
</html>
Run Example »
Search Order
If you have files with the same name, Django will use the first occurrence of the file.
The search starts in the directories listed in STATICFILES_DIRS
, using the order you have provided.
Then, if the file is not found, the search continues in the static
folder of each application.