Add CSS and Static Files in Django | Is Your CSS Not Loading?

Add CSS and Static Files in Django | Is Your CSS Not Loading?

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.

Setting Static URL in Django

Open 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 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 creating css as subdiectory inside static directory to add style.css.

Just like CSS, you can create the separate directory like ‘js’, ‘img’ to save JavaScript, 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

Including CSS in Django Template

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 the 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 below command.

python manage.py runserver

And open your project URL in the web browser.

You can see the your HTML template decorated with your style sheet.

Note: I tested this code and implementation in the Django 2.2 version and it is expected to work on any Django version.

Resolving 404 Not Found Error for Static Files

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.

Using findstatic option

Run manage.py with find static option.

If Django project able tp locate the CSS, it will return 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 not found, it will throw an err as “No matching file found”

$python manage.py findstatic css/style.css
No matching file found for 'css/style.css'.

Using Browser Console Output

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 Google Chrome browser,

  • right-click on browser window
  • select “inspect” or press ”Ctrl+Shift+I”
  • open “Console” tab in “inspect”
Django static CSS not found error in console

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 clearly mentioned that static file is not found.

There can be multiple reason if the Django is unable to loacte static files.

  • Check the static file directory and file names. I remember spending half an hour as I added .css explicitly in the file name and Django was reading this file as style.css.css.
  • Recheck all the static URLs and paths set in the settings.py

Understanding STATIC_ROOT and STATICFILES_DIRS

Don’t get confused with the STATIC_ROOT and STATICFILES_DIRS in settings.py.

When I faced the issue with my static, I dig 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 use.

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 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 problem adding static files in your Django project.

13 Comments

  1. 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.

    lt a href=" empty here " rel="nofollow ugc" gt        lt /a gt 

    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

    1. 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.

      {% load static %}
      
      style="background-image: url('{% static 'img/background.png' %}');"
      

      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

      path('index/', views.index, name='index'),
      

      The value of “name” should be “index”.

  2. 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

    HTML a tag - href="index' %}" rel="nofollow ugc" - MusiCoded 
    

    (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 🙂

    1. 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!

    2. Mr, I went to change the color of my page link or something else but is the same problem I can’t.

  3. 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 tag
    I hope it will help others as well thank you.

  4. Most of the tips are not actually help for my case but the simple changing the DEBUG = (TRUE)will make it possible for me.

Leave a Reply

Your email address will not be published. Required fields are marked *