In this Django Tutorial we are going to talk about Django Static Files, so when you are developing a website, generally we need to serve additional files such as images, CSS or JavaScript, in django these files are called static files. django provides django.contrib.staticfiles
to help you manage them.
When you are configuring static files make sure that you have these requirements.
- Make sure that
django.contrib.staticfiles
is included in yourINSTALLED_APPS
. - In your settings file, define
STATIC_URL
, for example:
1STATIC_URL = '/static/'
OK now create a new directory in your mysite project, or we can say in your project level directory. and also we are adding our style.css in css folder.
Basically we want to change our h1 and our p tag color, add this code in your style.css.
1 2 3 4 5 6 7 8 9 10 11 |
h1 { color:green } p { color:red } |
Now you need to open your settings.py in your django project, and add this code at the bottom.
1 2 3 |
STATICFILES_DIRS = [ BASE_DIR / "static", ] |
After that open your base.html and link your css file with your django project like this.
1 |
<link rel="stylesheet" href="{% static 'css/style.css' %}"> |
Also you need to load static at the top of your base.html, if you don’t do this you will receive error.
1 |
{% load static %} |
Now run your project this is the result.
So now these are our files for this tutorial.
mysite/static/css/style.css
1 2 3 4 5 6 7 8 9 10 11 |
h1 { color:green } p { color:red } |
mysite/templates/index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{% extends 'base.html' %} {% block title %} Home {% endblock %} {% block body %} <h1>Welcome to {{name}}</h1> <p>Tutorial Number 8 - Django static Files</p> {{pro_list}} {% endblock %} |
mysite/templates/base.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> {% block body %} {% endblock %} </body> </html> |
mysite/polls/views.py
1 2 3 4 5 6 7 8 9 10 |
from django.shortcuts import render # Create your views here. def Index(request): context = {"name":"Geekscoders.com", "pro_list":["Python", "Java", "C++", "C#"] } return render(request, 'index.html', context) |
mysite/polls/models.py
1 2 3 4 5 6 7 8 9 10 11 |
from django.db import models # Create your models here. class Question(models.Model): text = models.CharField(max_length=100) pub_date = models.DateTimeField('date published') def __str__(self): return self.text |
mysite/polls/urls.py
1 2 3 4 5 |
from django.urls import path from .views import Index urlpatterns = [ path('', Index, name = 'index') ] |
mysite/urls.py
1 2 3 4 5 6 7 |
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('polls.urls')) ] |