How to connect static files with Django

Vinoth Saravanan
2 min readApr 24, 2021

--

It looks like simple task to connect staticfiles (css, js, images) with django. But its tricky when you doing it improperly. With few lines code we can achieve it.

As a beginner, I had lots of lots of questions when started learning django. That is, where to create templates and static folder? either inside the app dir or outside the project dir.

So I surfed a lot in stack overflow and other forums. I can see more ways to do that. Each programmer doing in their own way. So i confused and tried all the instructions in one attempt and i failed. And i decided to follow each one at a time.

Its one of the method not a only one method.

First create a folders named templates and static inside the app directory. I’m using vs code editor.

Project name: dbtask, App name : dbtaskapp

Project Directory

Now we have to tell django where to find the static files and how to find them. In settings.py file, add the below code at bottom of the file. Before that, import os in top of the setting.py.

STATICFILES_DIRS = [os.path.join(BASE_DIR, “dbtaskapp/static”),]

To connect templates, in settings.py file we can see the variable named TEMPLATES. Inside that variable, edit

‘DIRS’ : [os.path.join(BASE_DIR,’dbtaskapp/templates’)]

Updating templates in settings.py

Now we need to load the static files in html page.

{% load static %}

<link rel=”stylesheet” href=”{% static ‘dbtaskapp/main.css’ %}”>

loading static files inside html

Yes, That’s it. Hope it will help to resolve your queries. Please do comment, if you facing any error regarding static files, I’ll try to resolve..

--

--

No responses yet