STATIC FILES IN DJANGO

Django

Static files are images, css, javascript files, fonts etc. in essence we turn to all those components that then represent the front-end part. Django in ready-to-use applications provides us with the django.contrib.staticfiles application that we need static files.

Static files
Static files

Let’s go to the settings.py file of the project and scroll the page until we find the STATIC_URL entry. Let’s specify the directory that will contain our static files, such as Bootstrap.

static file directory

Now let’s create the static folder in BASE_DIR remembering that this constant indicates the folders immediately under the root directory, therefore on the same level as templates.

Directory

Now let’s download the Bootstrap files and put them inside the static folder. Let’s open our homepage and go to call up the pre-installed application from Django that serves the static files by placing the following line of code at the top of the HTML document:

{% load static %}

HomePage

Once the link tag has been set to load Bootstrap’s css, we start the server and verify that everything works.

HomePage

As you can see the fonts used are those of Bootstrap so everything is working, for further confirmation right click on a point on the home page and select the item “View page source“. By opening the links you should see the Bootstrap css file.

inspect

In the same way, I could define a folder within the news application called static, create a style sheet that simply sets the color of the title h1 to green and have it loaded by the django.contrib.staticfiles application in the same way.

LINKS TO PREVIOUS POST

PREVIOUS POST LINKS

LINK TO THE CODE ON GITHUB

GITHUB