Adding Static Files To Django

Adding Static Files To Django

Things to do for static files rendering on the development environment

Hi,
As I mentioned in my last writing, nowadays I'm interested in Django. So, I started a demo project for Django. URLs, views and HttpResponses, and other things go very well.
When I get to render static entities (like CSS, JS, images, etc.), I got an error. The error I got django couldn't render static files. After I little time on it, I found the little error I made and I want to share it with you. I forgot to add {% load static %} tag to on top of my HTML file. But if you got similar errors like mine, now I want to emphasize the things you should do for the development environment. Of course the deployment and production environment will be different.

Things you should do for rendering static files:

1. Check your settings.py

Here there should be a Django app on your application settings installed apps.

INSTALLED_APPS = [
    ...,
    'django.contrib.staticfiles',
]

Also for development purposes there should be

STATIC_URL = '/static/'

in your settings.py file.

Your link should be like this

<link rel="stylesheet" href="{% static 'YOURAPPNAME/style.css' %}">

and on top of your HTML file, there should be

{% load static %}

line. I forgot this part and that is why I lost time.

3. Store your static file where Django recommend you to

This folder is under your application folder and named static folder. And inside this, you should name another folder with YOURAPPNAME. For example, let's say my application name is hello, so you should put your static files in hello/static/hello/style.css. Of course, you are able to add more subfolders here.

Django renders static files differently than normal HTML files.

For more detailed information please check the docs.

Thank you for reading.