Handling Static Files in Django
The CSS, images, javascript files required by a web page are called static files. Let's learn how to add these static files in Django
Step 1
Create a folder named 'static' in your app and add an image, a CSS file and a JavaScript file in it.
Your CSS file (Eg: mystyle.css) will look like this:-
body{
background-color:cadetblue;
font-family:"verdana";
}
Step 2
Your JS file (Eg: myscript.js) will look like this
document.getElementById("demo").innerHTML = "Welcome to ABC Company";
document.getElementById("demo").style.color = "white";
Step 3
Load and link your static files in your index template
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'mystyle.css' %}">
<title>Home Page</title>
</head>
<body>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
<a href="/contact">Contact</a>
</nav>
<h1>Home</h1>
<img src="{% static 'image.jpg' %}" alt="">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Obcaecati error
iusto quos veritatis tenetur eveniet totam cum neque quas voluptatibus quod dicta,
pariatur exercitationem sit perferendis reprehenderit ea fugit voluptatum.</p>
<script src="{% static 'myscript.js' %}"></script>
</body>
</html>
Step 4
Run the project and see the output
