0
0
Djangoframework~5 mins

Static files in templates in Django

Choose your learning style9 modes available
Introduction

Static files like images, CSS, and JavaScript make your web pages look good and work well. Django helps you include these files easily in your templates.

You want to add a logo image to your website header.
You need to apply styles using CSS files to your HTML pages.
You want to add interactive behavior with JavaScript files.
You want to organize your static files in one place for easy management.
Syntax
Django
{% load static %}
<img src="{% static 'path/to/file.jpg' %}" alt="description">
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
<script src="{% static 'js/script.js' %}"></script>

Always start your template with {% load static %} to use the static tag.

The {% static %} tag helps build the correct URL for your static files.

Examples
This adds a logo image from the images folder inside your static files.
Django
{% load static %}
<img src="{% static 'images/logo.png' %}" alt="Site Logo">
This links a CSS file to style your page.
Django
{% load static %}
<link rel="stylesheet" href="{% static 'css/main.css' %}">
This includes a JavaScript file for page behavior.
Django
{% load static %}
<script src="{% static 'js/app.js' %}"></script>
Sample Program

This template loads static files: a CSS file for styles, an image for the logo, and a JavaScript file for behavior. It shows how to organize and include static files in a Django template.

Django
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Static Files Example</title>
  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
  <header>
    <img src="{% static 'images/logo.png' %}" alt="Site Logo">
    <h1>Welcome to My Site</h1>
  </header>
  <script src="{% static 'js/script.js' %}"></script>
</body>
</html>
OutputSuccess
Important Notes

Make sure your static files are placed in the correct folders inside your Django app or project.

During development, Django serves static files automatically, but in production, you need to configure your web server to serve them.

Use the {% static %} tag instead of hardcoding URLs to keep your code flexible.

Summary

Use {% load static %} at the top of your template to enable static file usage.

Use {% static 'path/to/file' %} to get the correct URL for static files.

Static files include images, CSS, and JavaScript that improve your website's look and behavior.