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:
12STATIC_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:
12345678910111213141516171819202122232425262728293031323334βββ 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:
1234<head><link rel="stylesheet" href="{% static 'css/style.css' %}"><title>Linguist</title></head>
That is all! Enjoy it!
π