Django - Adding Static / Bootstrap

In last tutorial  we used HTML templet and used context to pass data in that templet. But when we need to integrate CSS or design in our templet we need to use static files and then import them in our HTML templet. CSS and JS are static data which doesn't need any processing from python. 

In this tutorial, we will add static files like CSS and JS in our HTML script and see how that works. These are static files and django have different way to manage static files.

Configure settings.py

To start with that first we need to configure locations of static files in the Django. We need to configure the URL path and static files location. By default, in Django URL path is configured at path '/static/'. We will use the same path for our demo. But for static file location, we will use a different path. Just like our templets we will create another directory in the project folder named static and put all static files in that folder.

Goto Settings.py files and look for STATIC_URL

STATIC_URL is URL path for your static files, when you call static files in URL or in the browser, it will use /static/.
e.g http:// <domain.com>/static/css/styles.css

STATICFILES_DIRS is location of your static files on server. By default STATICFILES are not configured so you need to add configuraion for STATICFILES.

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

Create Static files

Create a folder in project folder with name static (which we configured in STATICFILES_DIRS).

mkdir static

Create a css file in static directory and name it styles.css

Styles.css File

body {
background-color: powderblue;
}
h1 {
color: green;
}
p {
color: blue;
}

Configure HTML file

In HTML file first thing we will do is load static. 

{% load static %}

This will load static files in html templet.

Now when we define any statif file we just need to give path as below

<link rel="stylesheet" href="{% static 'styles.css' %}">

here we have provided href as add static path + styles.css. which will be more like /static/styles.css This will goto static directory and call styles.css file. So our html should look like.. 

{% load static %}
<html>
<head>
  <link rel="stylesheet" href="{% static 'styles.css' %}">
</head>
<body>

  <h1> Welcome to {{application_name}} </h1>
  <p>{{pdata}}</p>

</body>
</html>

Verify if your statif files work by browsing your page.. http:// 127.0.0.1:8000/stock/. 

Also you can verify static data using http:// 127.0.0.1:8000/static/styles.css

 

About the author

akarperiwal

0 Comments

Please login to comment