How to Load a CSS File in Django


In this article, we show how to load a CSS file in a template in Django.

Of course, loading CSS files is important because web pages are styled with CSS files.

Therefore, to give proper styling to a website to make it a beautiful site, loading CSS files into a Django template is vital.

CSS styles the web.

If you are familiar with HTML and CSS, you know what CSS files are declared in the head tag in HTML.

Thus, to load CSS files in a template in Django, we add the code to the head tag.

The code that we add to the head tag is shown below.

So let's now break down this code.

So the line, {% load staticfiles %}, loads all static files from the static directory in the app that are working with.

The next line, describes the link as a stylesheet and specifies the full path to the CSS file.

Since, the CSS file is located in the css directory which is located in the static directory, the full path is, static 'css/default.css'

So, in the first line of code, we import all static files, located in the static directory of the current app we are using. In our second line of code, we specifically say which file is the CSS file that is styling the current page. In this example, the file is default.css.

Static Directory

In Django's official documentation, it recommends that you keep all static files, such as images, videos, javascript files, CSS files, etc. in the static directory of the app you are using.

Say, let's say you create an App called Articles (where you keep the articles you write for your website). Inside of this app, you need to create a static directory. Inside of this static directory, you should create a directory called videos. Inside of this videos directory, you put all the videos for this Articles directory. You can then reference videos using the path described above, which again is, src="{% static 'videos\\video_to_display.png' %}"

One thing to check in your project directory is the file.

Make sure that in this file, normally present at the very end of the file, is the following statement shown below.

Without this line of code, Django will not know that the directory static contains the static files. So make sure that this line is present.

And this is all that you need to load a CSS file in Django.

Related Resources

How to Show All Tables of a MySQL Database in Python

How to Count the Number of Rows in a MySQL Table in Python

HTML Comment Box is loading comments...