Adding Templates and Static Files in Django

Subscribe to my newsletter and never miss my upcoming articles

Welcome to my .py series where I take you through what I learn weekly at She Code Africa Mentorship program Cohort 2-Python track. You can check below for other episodes.

This episode is about templates and static files in Django

The Django project structure is based on the M-V-T (Model-View-Template) Software Design pattern. In this article I will be taking you through:

  • Adding templates and static files

  • Creating a view and a URL pattern

In case you are not clear on the Django Project pattern, you can check my article here , which simply explains it.

Django mainly functions with backend, so to present it better to the user and provide a layout for the website, it makes use of templates.

A template contains the static part of the desired HTML output as well as some special syntax describing how dynamic content will be inserted

  • Django docs

In the last article , we successfully created a model. With the following steps, we will be adding templates and static files to the blog app. For this article, I downloaded a free bootstrap blog template .

1) Create a folder 'templates' under the blog app directory, then create another folder under templates and name it after the app name, in this case, 'blog'

  • Go to settings.py file, on TEMPLATES section add os.path.join(BASE_DIR,'templates') in DIRS

Adding this path, you define the directory where Django should look for the template files

2) Create a folder 'static' under the blog app, then under the static folder create another folder called 'blog' just like we did in the previous step.

In the settings.py file:

  • Define the static file

    STATIC_URL = '/static/'
    
  • Add the path

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

In Django, files such as Images, Javascript or CSS are referred to as static files

3) Now navigate to the bootstrap template you downloaded:

  • copy the index.html file and paste it in the templates/blog folder

  • copy the CSS and Vendor folder (contains CSS and Javascript) and paste in the static/blog folder

Your file arrangement should look like this:

Annotation 2020-08-05 150725.png

4) Create a new file base.html in template/blog folder

base.html file is a frame for all the pages in the app. It will contain stuff like the top navigation bar, the site footer. So any other page can use this instead of having to repeat the same HTML code (redundancy) in all pages.

5) Go to the index.html file, cut the header, top navbar, and footer leaving just the content section, then paste in base.html file.

Let's take a pause on the steps, then discuss the Django Template Language (DTL)

Django Template Language (DTL) is designed to strike a balance between power and ease. It's designed to feel comfortable to those used to working with HTML

So basically, the Django template has a special syntax (DTL) to implement templates. There are four(4) types of syntax in the Django template language. For this article I will just be using tags {% %}, you can check others here .

Now back to the steps,

6) Go to the base.html file:

  • On line 1 just before <!DOCTYPE html>, to load the static file, add this code

    {% load static %}
    
  • On the link and scripts tag, do a liking with the DTL tag and the file path like this:

 <!-- Bootstrap core CSS -->
  <link href="{% static 'blog/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">

  <!-- Custom styles for this template -->
  <link href="{% static 'blog/css/blog-home.css' %}" rel="stylesheet">

<!-- Bootstrap core JavaScript -->
  <script src="{% static 'blog/vendor/jquery/jquery.min.js' %}"></script>
  <script src="{% static 'blog/vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script>
  • Inbetween the header and footer add the block content tag:
{% block content %}


  {% endblock %}

{% block %} tag gives you the ability to specify parts of the base.html file that can be changed by pages that extend (use) it.

7) Go to the index.html file:

  • To tell the index.html file to use what is in base.html, add this code
{% extends 'blog/base.html' %}
  • Add this code to the start and end of the page content:
{% block content %}


  {% endblock %}

Let's take another pause and talk about views.

A view function or views is a Python function that takes a web request and returns a web response. This response can be the HTML contents of a web page or a redirect, or a 404 error or an image, etc.

  • Django docs

Annotation 2020-08-05 004540.png Image Source: The Net Ninja

So we want to write a view function to render the model and template we have added on the web.

Back to the steps:

8) Go to views.py under the blog app and create a view function:

from django.shortcuts import render
from .models import Article
from django.views.generic import ListView

# Create your views here.

class Homepage(ListView):
    model = Article
    template_name = "blog/index.html"

List view is a generic class-based view designed to display data as a page representing a list of objects

  • Django Docs

9) Go to urls.py file and create a URL pattern that will load what views.py has. Add the following code:

from django.urls import path
from .views import Homepage


urlpatterns = [
    path('',Homepage.as_view())

]

If you have followed these steps carefully, you have successfully added a template and static file to your app.

It doesn't matter if you downloaded a different template from the one used in this article, just be sure to follow the pattern, and you'd be good.

To appreciate all we have been coding, let's now run the server to view the blog.

10) Run this command in your terminal:

python manage.py runserver

Copy the HTTP address and run on your browser and you should see a beautiful output like mine or whatever you are creating.

Thanks for reading!

Feel free to check-in for the next article as I will be making the templates dynamic.

Refrences

Luiz Filipe da Silva's photo

Good explanation and simple steps. Thanks for sharing!

Ruth Ikegah's photo

Thanks Luiz Filipe da Silva, glad you found it useful

Bolaji Ayodeji's photo

This is amazing, well done!

Ogunade Adekunle's photo

I like how you outlined the process. great job!