Instagram
youtube
Facebook
Twitter

Static Files

In a web application, the looks matter the most. And, it is very much difficult to create a beautiful website using HTML only. So, how can we use CSS, Javascript, Images, videos, etc. in our web application? That's where the concept of static files comes in. 

Django provides a very convenient way to use these resources. django.contrib.staticfiles module helps us to manage these files easily. 

Django Static Files Setup

Step 1: Make sure django.contrib.staticfiles is already included in your settings.py installed apps. If not then please add it.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'YourAppName',
]

Step 2: Now, define your static URL in the settings.py file.

STATIC_URL = '/static/'

Step 3: Next, we have to add the STATICFILES_DIRS. This tells Django the location of our static files. Use the following expression to add this.

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

Step 4: Now, we have to add the STATIC_ROOT. This will be needed while the deployment of our web application. Use the given expression to add this.

STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')

Step 5: Create a static folder in your app. And create a static file inside your folder. I am creating main.css to store all the CSS.

Similarly, you can add images, javascript, and many more static files inside this folder.

Step 6: After adding static files load all of your static files in your templates folder by using the following expression.

{% load static %}

 

Adding CSS Files in the template

To load the static files. Add the given code to your HTML file.

<link rel="stylesheet" href="{% static 'main.css' %}">

After doing this write your CSS code. I’m adding CSS to my contact form which I had made in previous tutorials. 

So, I have already added my CSS files. Let's check if it is working or not.

 

Working Perfectly!

(Similarly, you can add Javascript too)

 

Adding Images in the template

To load the images. Add the given code to your HTML file.

<link rel="stylesheet" href="{% static 'img.png' %}">

My image name is img.png. Use your image name at that place.

Let's check if our image is loading or not.

Working Properly!