DEV Community

Cover image for Using Django Template Context
Samuel Mugane
Samuel Mugane

Posted on

Using Django Template Context

Introduction

Django has proven its resilience as a framework for web development. Django provides developers with a discrete playing field with powerful libraries that help cut down on development time. Django enables the developer to engage with both the client-side and the server-side in a well versed environment. In this article, we explore the Django template context that helps with rendering content to a template on the client-side.

Prerequisites

  1. Python 3.x
  2. Django
  3. Pip

Getting Started

As always, having a virtual environment set up is crucial as it helps with controlling code dependencies. So create a virtual environment using python venv a standard library for creating and managing virtual environments. Using terminal, implement the following steps.

  • Make new directory mkdir directoryname and cd into the new directory cd directoryname

  • Create virtual environment python3 -m venv myvenv

  • CD into the virtual environment cd myvenv

  • Activate virtual environment source bin/activate

Now install Django in new virtual environment

  • First, install pip sudo apt-get install python3-pip

  • Using pip, install Django framework pip3 install django

  • Verify installation django-admin --version

Set up Django project

  • With Django framework now installed, create Django project using django-admin startproject projectname

  • CD into the project created cd projectname

  • Make migrations for the database python3 manage.py migrate

  • Create super user for admin access using python3 manage.py createsuperuser and enter your username, email and password.

  • Now create your first Django app using python3 manage.py startapp appname

  • Start server python3 manage.py runserver and on your terminal you will get a link i.e http://127.0.0.1:8000/

  • When you click the link, you will be directed to a webpage on your browser and it should look as shown below:

Django successful install render

Rendering your first template

Django has a dynamic templating system that helps in rendering HTML files to the web.

Configuring settings.py file

Go to settings.py under your project folder and configure the INSTALLED_APPS list variable. Add 'my_app.apps.WebAppConfig' to the list variable.

Creating templates folder

In your app folder, create a new folder and name it templates. Inside the templates folder create another folder with the same name as your app name i.e if you app name is my_app the folder inside the templates folder should be my_app too.

Create an index.html file in the newly created folder.

Creating your first view

Go to views.py file in your app folder.

from django.shortcuts import render

def home(request):
    return render(request, 'my_app/index.html')
Enter fullscreen mode Exit fullscreen mode

In your app folder, create a urls.py file and initiate your home page route

from django.urls import path
from my_app.views home

urlpatterns = [
    path('', home, name='home'),
]
Enter fullscreen mode Exit fullscreen mode

In your project folder, edit the urls.py file to include the urls from your app.

from django import urls
from django.contrib import admin
from django.urls import path, include


urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('my_app.urls'))
]

Enter fullscreen mode Exit fullscreen mode

Using template context

The template context is a dictionary with variable names represented as key value pairs. It is initiated within a view function to pass content to be render to a webpage. For example, we want to render data from the database to a webpage. Let the data be personal information for users.

Let's create a model for users in models.py

from django.db import models

class Users(models.Model):
    fullname = models.CharField(max_length=100)
    email = models.CharField(max_length=50)
    mobile = models.CharField(max_length=15)
Enter fullscreen mode Exit fullscreen mode

Make migrations to database:

python3 manage.py makemigrations
python3 manage.py migrate
Enter fullscreen mode Exit fullscreen mode

To render the data, we can add the context to the home view function as follows:

from multiprocessing import context
from django.shortcuts import render
from .models import Users

def home(request):
    context = {'users_list': Users.objects.all()}
    return render(request, 'my_app/index.html', context)
Enter fullscreen mode Exit fullscreen mode

In the index.html file, we can use template tags to render the user information as follows:

<!--Users Table-->

<div class="row">
    <div class="table-responsive bg-white my-3" style="border-radius: 5px;">
    <div class="title fw-bold fs-3">
        Users List
    </div>
    <table class="table table-striped">
        <thead class="border-bottom font-weight-bold">
        <tr
            <td>Full Name</td>
            <td>Mobile</td>
            <td>Email</td>
        </tr>
        </thead>
        <tbody>
        {% for user in users_list %}
        <tr>
            <td>{{user.fullname}}</td>
            <td>{{user.mobile}}</td>
            <td>{{user.email}}</td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
    </div>
</div>
Enter fullscreen mode Exit fullscreen mode

All the user information will be render on the webpage inform of a table. The {{user.fullname}} will be replaced by the fullname of the user and the same is true for the other variable names.

Conclusion

The template context's functionality helps in rendering content to a webpage in a quick and efficient manner. You can learn more about Django template context here.

Top comments (0)