Skip to main content

Command Palette

Search for a command to run...

Handling Static files in Django

Updated
3 min read
Handling Static files in Django

Static files in Django refer to files that do not change and are served directly to the user. These files include things like CSS stylesheets, JavaScript files, images, fonts, and other resources that are used to enhance the look and functionality of a web application. Unlike media files, which are user-uploaded and can vary, static files are usually the same for all users and are served in their original form.

Scenario: Building a Simple Webpage with Static Files

Link to project

Step 1: Create a New Django Project and App

Make a folder

mkdir my_project

Go to that folder

cd my_project

Make virtual environment

python -m venv envname

Activate the environment and install django

IN WINDOWS

.\envname\Scripts\activate

In Unix/Linux Systems

source envname/bin/activate

Install django

pip install django
  1. Create a new Django project:

     django-admin startproject my_project .
    
  2. Create a new app within the project:

     python manage.py startapp my_app
    
  3. Add the new app toINSTALLED_APPS in settings.py:

     # settings.py
     INSTALLED_APPS = [
         ...
         'my_app',
     ]
    

Step 2: Create Static Files Directory and Files

  1. Create astatic directory in the project root:

     |-- my_project/
     ├── my_app/
     ├── static/
     │   ├── css/
     │   │   └── style.css
     │   ├── js/
     │   │   └── script.js
     │   └── images/
     │       └── logo.png
     ├── manage.py
     └── db.sqlite3
    
  2. Create CSS file (static/css/style.css):

     /* static/css/style.css */
     body {
         background-color: #f0f0f0;
         font-family: Arial, sans-serif;
     }
    
     h1 {
         color: #333;
     }
    
  3. Create JavaScript file (static/js/script.js):

     // static/js/script.js
     document.addEventListener('DOMContentLoaded', function() {
         console.log("HELLO DJANGO FORM JS");
     });
    
  4. Add an image (static/images/logo.png):

    (Add any logo image you have.)

Step 3: Configure Settings

  1. Configuresettings.py for static files:

     # settings.py
     STATIC_URL = '/static/'
     STATICFILES_DIRS = [
         BASE_DIR / "static",
     ]
    
  2. Configure settings.py for template folder

     TEMPLATES = [
         {
             'BACKEND': 'django.template.backends.django.DjangoTemplates',
             #update here
             'DIRS': [BASE_DIR/"templates"],
             'APP_DIRS': True,
             'OPTIONS': {
                 'context_processors': [
                     'django.template.context_processors.debug',
                     'django.template.context_processors.request',
                     'django.contrib.auth.context_processors.auth',
                     'django.contrib.messages.context_processors.messages',
                 ],
             },
         },
     ]
    

Step 4: Create a Template

  1. Create a template directory in the app:

     my_project/
     ├── templates/
     │   └── index.html
    
  2. Create the HTML template (templates/index.html):

     {% 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" type="text/css" href="{% static 'css/style.css' %}">
     </head>
     <body>
         <h1>Hello, Django!</h1>
         <img src="{% static 'images/logo.png' %}" alt="Logo">
         <script type="text/javascript" src="{% static 'js/script.js' %}"></script>
     </body>
     </html>
    

Step 5: Create a View and URL

  1. Create a view inmy_app/views.py:

     from django.shortcuts import render
    
     def index(request):
         return render(request, 'index.html')
    
  2. Create a URL pattern inmy_app/urls.py:

     from django.urls import path
     from .views import index
    
     urlpatterns = [
         path('', index, name='index'),
     ]
    
  3. Include the app's URLs in the project'surls.py:

     # my_project/urls.py
     from django.contrib import admin
     from django.urls import path, include
    
     urlpatterns = [
         path('admin/', admin.site.urls),
         path('', include('my_app.urls')),
     ]
    

Step 6: Run the Development Server

  1. Run the development server:

     python manage.py runserver
    
  2. Open a web browser and navigate tohttp://127.0.0.1:8000/.

You should see a styled page with an Console message saying "Hello, Django from JS" and an image displayed. The CSS file is applied for styling, the JavaScript file for the alert, and the image file is displayed from the static directory.

💡
Open Inspect and Console to see JS output message

More from this blog

Aarav's Blogs

19 posts