Python Django – How to add css to django application

So, some time ago I have started to create apps in Django with Python. It is really fun and amazing, what one can achieve with this package 🙂

Python

E.g., I have generated a small app, counting words and analyzing their repeatability, but I will write about it later. Now, you can take a look at GitHub, if you want to.

Anyway, as soon as I started with writing HTML in Django, the first thing I have encountered is that it is not that easy to add a separate style.css file to it. I was adding it with the standard way, but it simply was not working. Thus, I have decided to make a small research in the net, and it seemed to be quite a big issue for some people as well. I have tried some of the recipes, but it did not work out as I wanted it to. Thus, today, while I was looking for some information for staticfiles in Django, I found a way to do it and I managed it 🙂

So, for all the people out there, who try to search for “how to add css to django”, here is the correct sequence:

  1. At the bottom of the file settings.py, write the following:
    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR,  'static')
    

    The first line should be there, so just add the second line.

  2. In the folder of the django app, create a folder named “static”. You can find the exact location of my static folder from my app for counting words here:
    ├── db.sqlite3
    ├── manage.py
    ├── wordapp
    │   ├── __init__.py
    │   ├── __pycache__
    │   │   ├── __init__.cpython-34.pyc
    │   │   ├── settings.cpython-34.pyc
    │   │   ├── urls.cpython-34.pyc
    │   │   └── wsgi.cpython-34.pyc
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    └── wordcountapp
        ├── admin.py
        ├── __init__.py
        ├── migrations
        │   ├── __init__.py
        │   └── __pycache__
        │       └── __init__.cpython-34.pyc
        ├── models.py
        ├── __pycache__
        │   ├── admin.cpython-34.pyc
        │   ├── __init__.cpython-34.pyc
        │   ├── models.cpython-34.pyc
        │   ├── urls.cpython-34.pyc
        │   └── views.cpython-34.pyc
        ├── static
        │   └── css
        │       └── style.css
        ├── templates
        │   └── index.html
        ├── tests.py
        ├── urls.py
        └── views.py
    
  3. So far so good. Now go to the html file in the templates folder (in my app it is index.html), open it and on the top of it write “{% load staticfiles %}”. Write this even before openning the tag, write it on the first line.
  4. Then within the <head></head> tag write  <link rel=”stylesheet” href=”{% static ‘css/style.css’ %}”> My head tag currently looks like this:
      <head>
        <link rel="stylesheet"  href="{%  static  'css/style.css'  %}">
        <title>Linguist</title>
      </head>
    

That is all! Enjoy it!

🙂