As a part of the Django tutorial series, we will learn to add CSS and other static files in Django. We will also see how you can debug if your static files are not properly loading in the Django template.
Table of Contents
Open the setting file (settings.py
) in your Django project and set STATIC_URL
and STATICFILES_DIRS
variables.
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static/"), )
BASE_DIR
is the path to the Django project files. It might be already defined in the settings.py. Otherwise, you can set it.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Now include django.contrib.staticfiles
in the INSTALLED_APPS
list in settings.py
.
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # newly added 'registration', 'myapp', ]
Make a new directory named ‘static’ inside the project directory. And add all your static files including CSS, images, and JavaScript.
Here we are adding CSS ‘style.css’ in the static directory. To make it more organized, we created CSS as a subdirectory inside the static directory to add style.css.
Just like CSS, you can create separate directories like ‘js’, ‘img’ to save JavaScript and images in the static directory.
Here is the structure of the project directory after adding CSS.
├───myapp │ ├───migrations │ ├───templates ├───static │ └───css | └───style.css └───myproject ├───templates └───registration
We need to load the static files by adding the below line of code at the top of the template (.
html) file.
{% load static %}
Then, insert the stylesheet in the HTML using link
HTML tag.
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/>
If you are new to HTML and CSS, you can learn more about adding CSS in HTML code.
You have done with all the settings.
Start your project by running the below command.
python manage.py runserver
Open your project URL in the web browser.
You can see your HTML template decorated with your style sheet.
Note: I tested this code and implementation in the latest Django version and it is expected to work on any Django version.
If your project is unable to locate the CSS or any other status files inside your project directory, it will throw HTTP 404 status code as an error.
Is your Django CSS not loading?
There are multiple ways of debugging it.
Run manage.py with the find static option.
If the Django project is able to locate the CSS, it will return the path to your CSS file.
$ python manage.py findstatic css/style.css Found 'css/style.css' here: <path_to_your_CSS_file>
If the CSS static file is not found, it will throw an error as “No matching file found”
$python manage.py findstatic css/style.css No matching file found for 'css/style.css'.
If you see your CSS or static files are not added properly, you can check the browser console output.
To see the console output in the Google Chrome browser,
You can see the error message.
GET http://127.0.0.1:8000/static/css/style.css net::ERR_ABORTED 404 (Not Found)
It has been mentioned that a static file is not found.
There can be multiple reason if the Django is unable to locate static files.
Don’t get confused with the STATIC_ROOT and STATICFILES_DIRS in settings.py.
When I faced the issue with my static, I dug into the internet. After reading through multiple pages, I found it more confusing. So, I just want to make it simple and clear for you.
Both of these paths have different uses.
STATICFILES_DIRS
You can keep the static files in multiple directories. For example, you might want to keep one static file directory for each Django app. In this case, you can list down all the static file paths inside in STATICFILES_DIRS list.
STATIC_ROOT
If your project is under development, you don’t need to set STATIC_ROOT in Django settings. This path is used when you deploy your project.
When you run the below command, it will collect all the static files into the STATIC_ROOT path directory.
python manage.py collectstatic --noinput
Keeping all the static files in one directory is useful to secure your files in production.
This is all about how to add CSS in Django. Similarly, you can add other static files like JavaScript, Images, etc. Let me know if you are facing any problems adding static files in your Django project.
Hi, I am actually struggling with the fact that my background.png, no matter what I try, will not load on-site.
Here’s the situation : Music(app) – static- music- images(background.png) / style.css
Now, in style.css, I tried multiple solutions, see below, but none work:
I read about others having the same issue no matter what they tried.
The above article info doesn’t seem to apply to my situation. hmm
body{
cover { background: url(‘/static/img/background.png’);}
background:url(‘../img/background.png’)
}
…………………………………………………………………………………………………………….
And with this occasion, allow me to ask about another interesting fact I came across and not yet manage to understand what it is, but I made it work by leaving empty the field wherein the tutorial was filled with:
href=”{% url ‘music:index’ %}”
index.html I put spaces coz it seems it won’t load the code when I publish the comment.
THE ERROR on site:
NoReverseMatch at /music/
Reverse for ‘index’ not found. ‘index’ is not a valid view function or pattern name.
I’d really appreciate your view.py or opinion.py regarding these matters 🙂
Nice site, btw. I just came across your site and the info looks recognizable(organized) by me, a beginner, which I guess is a good thing 🙂
Cheers and thanks,
Adina
Hi Adina,
I’m very glad you find our platform valuable for your learning.
Regarding your query, I think you are not able to set the background image. This is more likely because you are trying to access the background.png image in the CSS file using the URL function which you cannot access there.
Just to make sure, you check the source code of that page and see what URL is showing.
Here is the probable solution to the problem.
Instead of setting background image in CSS, set that in an HTML template file using inline CSS code.
Let me know if this works.
————-
Regarding other findings…
The information you provided is not sufficient to dig. What I can say is that check the url.py
The value of “name” should be “index”.
Hi,
THANK YOU so much for your reply.
Regarding the background image, eventually, I managed to load an image directly from the internet, without using the saved image in /music/static/images.
If I remember well, in the HTML file, it doesn’t work to put the image. The code line would appear on the site’s top of page:)))))
So I have this :
style.css
body{
background: url(“https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTIKBRRyy_Hl60hXuxoq0PRS_Zhw8nyvCHRoA&usqp=CAU”)
}
…………………………………………………………………………………….
Now, regarding the index matter, I see it works this way, at least no error anymore, hihihi 😀 :
music/urls.py
urlpatterns = [
# /music/
path(” “, views.index, name=’index’), (no index between ” “, coz it’ll show error )
index.html
(now it works with {% url ‘music:index’ %} ,before it would work with href=’ ‘ )
What do you think? 🙂
I sensed it must have been related to urls.py and even looked to that line(just looked…:)) ), but I wasn’t sure, and coz I couldn’t find a clear answer I remained wrapped in mystery.
Now I can continue my learning, even though this is learning too :))
I got myself hit by the ambition to learning to code even if I am self-taught and have studied music before. Maybe later, an internship, some more advanced courses. Pff 🙂
Any advice regarding the order of the information I should learn? I am asking because a course, for ex, follows a systematic curriculum, but being self-taught, sometimes it feels like swimming in an ocean of info I have to search, differentiate(for my needs). This can cut a bit the learning flow, but on the other hand, I am encouraged by the fact that my intuition seems to help me.
Thank you so much, again. And keep in touch.
Have a nice time there Aniruddha:)
PS Hopefully I didn’t bore you with this kilometric comment 🙂
You’re welcome, Adina! I’m glad you find the solution to your background image problem. And hope it is solved now.
Regarding, second matter, {% url ‘music:index’ %} is used to get the URL link. We can use this tag anywhere in the HTML template. href=” is the HTML attribute associated with HTML ‘a’ tag. Both serve a different purpose.
Learn to code is all about the process. If you enjoy doing it, you will keep learning. I like your spirit. Be with that.
You will find tones of information to learn and sometimes to get lost 😀 So you should have proper agenda and a planned out carriculum. I would like to help you but I’m not sure your purpose behind learning and what you want to accomplish. But as I see you are learning Django, learn some basic HTML and CSS tags (if you are not familiar with). We also have Python group on Facebook where we discuss different topics.
No worries! We will be in touch through this blog 😀 Feel free to drag me if you stuck 😉
Take care and keep coding!
Mr, I went to change the color of my page link or something else but is the same problem I can’t.
After so many attempts I tried different methods to make an image as my background, it didn’t work but finally, I used your code it didn’t work at first when I used it after
{% load static %}
on the page but it worked when I loaded it inside the body tagI hope it will help others as well thank you.
I’m glad you find the solution. And thanks for sharing. It will help others.
Thanks for the tips.The problem is solved
hope you get more to share THANKS!!
I’m glad your problem is solved. Keep sharing your progress with us.
I was struggling with this and your solutions worked! Thanks alot!
You’re welcome, Bryan! I’m glad this solution solved your problem. Hope you enjoy following my other tutorials as well.
Most of the tips are not actually help for my case but the simple changing the DEBUG = (TRUE)will make it possible for me.
While development, it is always good to turn on debug mode for ease of development.