Adding Styles to Django Templates

django add styles to project
10 November 2024

When working with Django and you want to add your own styles to your template, it might seem a bit complicated at first, but in reality it isn’t that hard. In this text, we'll go over how to add CSS styles to Django templates and explain how it works with this popular framework, seemingly creating an attractive design for your website.

Indeed, Django is one of the favorite frameworks for web development, built on the Python programming language, and one of its great features is that with the use of templating and adding static files and external JavaScript, you can create visually appealing websites.

In order for this to work, you need to create your own static directory. For example, using a directory called 'static' allows you to place your CSS and JS files in it, and then access them through Django templates. This enables you to manage those files without needing to write long static code directly in HTML so that your website is easier to manage.

One important thing when working with static files in Django is that you should definitely adjust your static file settings properly so that those files can be accessed correctly. This task is very simple and can be done using different methods, however, there is a standard way where you should consider using template tags and context processors in your template.

We should examine a simple code that accurately illustrates how to implement styles without forgetting to provide its explanations.

{% load static %}




My Django Project






Now let's review this code line by line:

{% load static %}: This line is a tag that enables static file loading which is necessary for including your static files.
<!DOCTYPE html>: This line defines the document type of HTML.
<html lang="fa">: This HTML tag sets the language to Persian.
<head>: The head tag is used for metadata and various links, like the CSS style sheet.
<meta charset="UTF-8">: This sets the page character encoding to UTF-8, which is a universal character set.
<title>My Django Project</title>: This specifies the title of the site that appears on the browser tab.
<link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">: This links to the CSS file located in the static directory.
<body>: This is where the main content of the page will be placed.
<h1>Welcome to Django Template!</h1>: This specifies the main heading of the page.
</body>: This marks the end of the body tag and all the main content structure of the page.
</html>: This marks the end of the HTML document.

FAQ

?

How can I import CSS files into Django?

?

Why aren't my static files rendering in Django?

?

When should I use static files in Django?