Working with Django Static files

Any website need some standard files which are use across such as style sheet and JavaScript files, different style or JavaScript libraries.  Django provides  django.contrib.staticfiles to help you manage them.

By default django.contrib.staticfiles is included in INSTALLED_APPS, just make sure it there.

Following statement will be present at the end of settings.py file

STATIC_URL = '/static/'

Now create a folder name static under application (in current case polls). Create application folder under static again. The folder structure will look like below


├── mysite03
│   ├── db.sqlite3
│   ├── manage.py
│   ├── mysite03
└── polls
    └── static
    │   └── polls
    ├── templates
        └── polls

Here you can copy any file that you want to use. As a standard practice, you should create separate folders for css, js and img for stylesheets, JavaScript and images

Let me copy an image to static folder and display it on webpage. Here is the code

{% extends "polls/base.html" %}

{% load static %}

{% block content %}

<h>This is content Block from polls/fifth.html file </h>

<imgsrc="{% static 'polls/img/tiger-beside-green-plants-standing-on-brown-land-during-145899.jpg' %}"alt="My image"width="500"height="500">

{% endblock %}

Here is the output


Besides static files inside you application, you might have static files at project level or even at organization level, Django provides a facility to define these locations as static directory by adding following code in settings.py. You can define a list of directories (STATICFILES_DIRS) in your settings file where Django will also look for static files.

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    '/var/www/static/',
]

Here BASE_DIR is nothing but your project home directory. I have created another static folder and copied an image of an elephant there. Template page looks as below

{% extends "polls/base.html" %}

{% load static %}

{% block content %}

<h>This is content Block from polls/fifth.html file </h>

<imgsrc="{% static 'polls/img/tiger-beside-green-plants-standing-on-brown-land-during-145899.jpg' %}"alt="My image"width="500"height="500">

<imgsrc="{% static 'img/elephant-1822636_1280.jpg' %}"alt="My image"width="500"height="500">

{% endblock %}

here is the output

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.