How to connect static files with Django

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..

--

--

--

Live.Love.Learn

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

NavigableSet(I)| java collection

Gutenberg Tutorials: #3 Attributes — Demonstrated and Explained

Create a Dark Mode of your app using Styled Components

This is my second Post is medium

Ilya and Queries | CF

Knex Migration —  For schema and seeds with PostgreSQL.

Naming of @Output events in Angular

Don’t Use Notepad For Notes, Use a Markdown Editor

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vinoth Saravanan

Vinoth Saravanan

Live.Love.Learn

More from Medium

How To Manage Static Files in Your Django Project

Calling REST API with JWT Authentication in Django

Most useful Array methods in Javascript ( filter  — part 2)

Deploying react and django rest framework with nginx and gunicorn