When I use {% load static %}
and then add an image like this to my template:
<img src="{% static 'logo.png' %}">
I only get the image if it's stored in a direction called static
which is in the same app. But I want to use the logo for the whole project, and, also in a template for the whole project. It doesn't work when the image is stored in a static
direction which is in the inner project folder.
How do I use static files for the whole project? And how to acces them from the template? (I'm a hobby developper and so not in production ;-)) My settings are nearly the one they were when I created the project. (I only added some additional template direction.)
Thank you for reading this
If you want to use static files in your Django project
, you have to realize several steps :
Step 1 : INSTALLED_APPS in settings.py
Make sure that you have django.contrib.staticfiles
in INSTALLED_APPS
Step 2 : STATIC_URL
Then, in settings.py file you have to write this : STATIC_URL = '/static/'
Now, in your Django application, you can create a new repository named static
and put your static elements inside.
If you want to call on of this element :
{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image"/>
STEP 3 (What do you want) : STATICFILES_DIRS
If you have some static elements which are not for a particular Django application, you can use STATICFILES_DIRS
.
You can create a new repository beside Django applications repository : static
.
You will get :
My_project
|
__ application 1
|
__ application 2
|
__ ...
|
__ static
In settings.py file, please add :
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'path_to_static_directory/static/',
]
Now, you can access to static files in any templates just by loading static files : {% load static %}
.
Please, read this tutorial : https://docs.djangoproject.com/en/1.10/howto/static-files/