Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Static File Storage in Django

Introduction

Static files are an essential part of any web application. These include JavaScript files, CSS files, and images that are required for the front-end of the application. In Django, managing static files is straightforward and built into the framework. This tutorial will guide you through the process of setting up and managing static files in a Django project.

Setting Up Static Files

First, you need to configure your Django project to properly handle static files. This involves setting the STATIC_URL and STATICFILES_DIRS in your project's settings.

Edit the settings.py file to include the following settings:

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    BASE_DIR / "static",
]
                    

Creating Static Files

Next, you need to create a directory named static in your Django app where you will store all your static files. For example, if you have an app named myapp, you should create a directory structure like this:

Create the static directory:

myapp/
    static/
        myapp/
            css/
            js/
            images/
                    

Referencing Static Files in Templates

Now that you have set up your static files directory, you can reference these files in your templates. Use the {% load static %} tag at the top of your template file to load static files and the {% static 'path/to/file' %} tag to reference them.

Example template:

{% load static %}




    
    My Page
    


    

Welcome to My Page

Logo