0
0
Djangoframework~5 mins

Static files in development in Django

Choose your learning style9 modes available
Introduction

Static files are images, CSS, and JavaScript that make your website look nice and work well. During development, Django helps you serve these files easily without extra setup.

When you want to add styles to your website using CSS during development.
When you need to include images or icons in your pages while building your app.
When you want to test JavaScript features locally before going live.
When you want to see how your static files affect your site without deploying.
When you want to organize your static files in your Django project for easy access.
Syntax
Django
1. In settings.py, add:

STATIC_URL = '/static/'

2. Place your static files inside an app folder named 'static', e.g., myapp/static/myapp/style.css

3. In your template, load static and use:

{% load static %}
<link rel="stylesheet" href="{% static 'myapp/style.css' %}">

The STATIC_URL setting tells Django where to find static files in URLs.

Use the {% load static %} tag in templates to access static files easily.

Examples
Load an image named logo.png from the static/images folder.
Django
{% load static %}
<img src="{% static 'images/logo.png' %}" alt="Logo">
Include a JavaScript file app.js from the static/js folder.
Django
{% load static %}
<script src="{% static 'js/app.js' %}"></script>
Basic setting to define the URL prefix for static files.
Django
STATIC_URL = '/static/'
Sample Program

This example shows how to set STATIC_URL, organize static files inside an app, and use them in a template. When you run the Django development server, it will serve the CSS file automatically, and the page background will be light blue with a green heading.

Django
# settings.py snippet
STATIC_URL = '/static/'

# Directory structure:
# myproject/
# ├── myapp/
# │   └── static/
# │       └── myapp/
# │           └── style.css
# └── templates/
#     └── base.html

# base.html content:
"""
{% 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 'myapp/style.css' %}">
  <title>Static Files Demo</title>
</head>
<body>
  <h1>Welcome to Static Files Demo</h1>
</body>
</html>
"""

# style.css content:
"""
body {
  background-color: #e0f7fa;
  font-family: Arial, sans-serif;
}
h1 {
  color: #00796b;
}
"""
OutputSuccess
Important Notes

During development, Django automatically serves static files if DEBUG = True.

In production, you need a web server or service to serve static files separately.

Keep static files organized inside each app's static folder to avoid conflicts.

Summary

Static files are needed for styling and scripts in your Django app.

Use STATIC_URL and the {% static %} template tag to include them.

Django serves static files automatically during development for easy testing.