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 π
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:
- 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.
- 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 - 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.
- 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!
π
