Templates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the backend, templates are used to render dynamic content and define the visual structure of a web page.
Django provides two ways to organize templates, depending on the project's size and structure:
- A project-level template directory, shared across all apps.
- App-level template directories, useful in large projects or when different layouts are needed for different apps.
Template Setup in Django
In this guide, we’ll create a single template directory at the project level for simplicity. This means all templates will be stored in one central location.
Configuration in settings.py
To configure templates, open the settings.py file of your project. Create a folder named templates in the base directory (BASE_DIR) and update the TEMPLATES setting as follows:
Python
TEMPLATES = [
{
# Template backend to be used, For example Jinja
'BACKEND': 'django.template.backends.django.DjangoTemplates',
## Path definition of templates folder .
'DIRS': [BASE_DIR/'templates'],
'APP_DIRS': True,
# options to configure
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Using Django Templates
Let's look at an example to understand how Django templates work with views and URLs. Templates are not limited to displaying static HTML- they can also present dynamic data passed from views via a context dictionary.
Refer to the following articles to check how to create a project and an app in Django.
Consider an example project called "geeksforgeeks" with an app named "geeks":
views.py
We’ll define three views in geeks/views.py:
- simple_view: Renders geeks.html with static content.
- check_age: Processes a form input to check a user's age using conditional rendering.
- loop: Sends a list and a string to loop.html for iteration.
Python
from django.shortcuts import render
from .forms import AgeForm
def simple_view(request):
data = {"content": "Gfg is the best"}
return render(request, "geeks.html", data)
def check_age(request):
age = None
if request.method == 'POST':
# request.POST.get returns a string, default to "0"
age = int(request.POST.get('age', 0))
return render(request, 'check_age.html', {'age': age})
def loop(request):
data = "Gfg is the best"
number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
context = {
"data": data,
"list": number_list
}
return render(request, "loop.html", context)
urls.py
Define the URL patterns in your app’s urls.py file to link each view to a specific route:
Python
from django.urls import path
from mini import views # Assuming your app is named 'mini'
urlpatterns = [
path('simple', views.simple_view),
path('condition', views.check_age),
path('loop', views.loop),
]
Template Files
geeks.html
Displays the message passed from the simple_view.
Location: "app_name/templates/geeks.html"
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homepage</title>
</head>
<body>
<h1>Welcome to GeeksforGeeks.</h1>
<p>{{ data }}</p>
</body>
</html>
check_age.html
Accepts user input and displays a message based on the entered age using if conditions.
Location: "app_name/templates/check_age.html"
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Age Checker</title>
</head>
<body>
<h1>Welcome to the Age Checker</h1>
<form method="post">
{% csrf_token %}
<label for="age">Enter your age:</label>
<input type="number" id="age" name="age" required>
<button type="submit">Check Age</button>
</form>
{% if age is not None %}
<p>Your age is: {{ age }}</p>
{% if age >= 20 %}
<p>You are an adult.</p>
{% else %}
<p>You are not an adult.</p>
{% endif %}
{% endif %}
</body>
</html>
loop.html
Uses a for loop and if condition to display even numbers from a list.
Location: "app_name/templates/loop.html"
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Even Numbers</title>
</head>
<body>
<h1>{{ data }}</h1>
<p>Even Numbers:</p>
<ul>
{% for number in list %}
{% if number|divisibleby:2 %}
<li>{{ number }}</li>
{% endif %}
{% endfor %}
</ul>
</body>
</html>
Output:
Snapshot of /simple endpoint
Snapshot of /condition endpoint
Snapshot of /loop endpointNote: You can also follow the convention app_name/templates/app_name/template_name.html and then reference it in views as app_name/template_name.html. This is the traditional and recommended structure.
The Django template language
This is one of the most important facilities provided by Django Templates. A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. As we used for the loop in the above example, we used it as a tag. similarly, we can use various other conditions such as if, else, if-else, empty, etc. The main characteristics of Django Template language are Variables, Tags, Filters, and Comments.
Jinja Variables
Variables output a value from the context, which is a dict-like object mapping keys to values. The context object we sent from the view can be accessed in the template using variables of Django Template. Syntax:
{{ variable_name }}
Example: Variables are surrounded by {{ and }} like this:
My first name is {{ first_name }}. My last name is {{ last_name }}.
With a context of {'first_name': 'Naveen', 'last_name': 'Arora'}, this template renders to:
My first name is Naveen. My last name is Arora.
To know more about Django Template Variables visit - variables – Django Templates
Tags provide arbitrary logic in the rendering process. For example, a tag can output content, serve as a control structure e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags. Syntax:
{% tag_name %}
Example: Tags are surrounded by {% and %} like this:
{% csrf_token %}
Most tags accept arguments, for example :
{% cycle 'odd' 'even' %}
Filters
Django Template Engine provides filters that are used to transform the values of variables and tag arguments. We have already discussed major Django Template Tags. Tags can’t modify the value of a variable whereas filters can be used for incrementing the value of a variable or modifying it to one’s own need. Syntax:
{{ variable_name | filter_name }}
Filters can be “chained.” The output of one filter is applied to the next. {{ text|escape|linebreaks }} is a common idiom for escaping text contents, then converting line breaks to <p> tags. Example:
{{ value | length }}
If value is ['a', 'b', 'c', 'd'], the output will be 4.
Template ignores everything between {% comment %} and {% end comment %}. An optional note may be inserted in the first tag. For example, this is useful when commenting out code for documenting why the code was disabled. Syntax:
{% comment 'comment_name' %}
{% endcomment %}
Example :
{% comment "Optional note" %}
Commented out text with {{ create_date|date:"c" }}
{% endcomment %}
To know more about using comments in Templates, visit comment – Django template tags
Template Inheritance
The most powerful and thus the most complex part of Django’s template engine is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. extends tag is used for the inheritance of templates in Django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables. Syntax:
{% extends 'template_name.html' %}
Example: Assume the following directory structure:
dir1/
template.html
base2.html
my/
base3.html
base1.html
In template.html, the following paths would be valid:
HTML
{% extends "./base2.html" %}
{% extends "../base1.html" %}
{% extends "./my/base3.html" %}
To know more about Template inheritance and extends, visit extends – Django Template Tags
Similar Reads
Django Tutorial | Learn Django Framework
Django is a Python framework that simplifies web development by handling complex tasks for you. It follows the "Don't Repeat Yourself" (DRY) principle, promoting reusable components and making development faster. With built-in features like user authentication, database connections, and CRUD operati
10 min read
Django Basics
Django Basics
Django is a Python-based web framework which allows us to quickly develop robust web application without much third party installations. It comes with many built-in featuresâlike user authentication, an admin panel and form handlingâthat help you build complex sites without worrying about common web
3 min read
Django Installation and Setup
Installing and setting up Django is a straightforward process. Below are the step-by-step instructions to install Django and set up a new Django project on your system.Prerequisites: Before installing Django, make sure you have Python installed on your system. How to Install Django?To Install Django
2 min read
When to Use Django? Comparison with other Development Stacks
Prerequisite - Django Introduction and Installation Django is a high-level Python web framework which allow us to quickly create web applications without all of the installation or dependency problems that we normally face with other frameworks. One should be using Django for web development in the
2 min read
Django Project MVT Structure
Django follows the MVT (Model-View-Template) architectural pattern, which is a variation of the traditional MVC (Model-View-Controller) design pattern used in web development. This pattern separates the application into three main components:1. ModelModel acts as the data layer of your application.
2 min read
How to Create a Basic Project using MVT in Django ?
Prerequisite - Django Project MVT Structure Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server. Create a basic Project: To in
2 min read
How to Create an App in Django ?
In Django, an app is a web application that performs a specific functionality, such as blog posts, user authentication or comments. A single Django project can consist of multiple apps, each designed to handle a particular task. Each app is a modular and reusable component that includes everything n
3 min read
Django settings file - step by step Explanation
Once we create the Django project, it comes with a predefined Directory structure having the following files with each file having its own uses. Let's take an example // Create a Django Project "mysite" django-admin startproject mysite cd /pathTo/mysite // Create a Django app "polls" inside project
3 min read
Django view
Views In Django | Python
Django Views are one of the vital participants of the MVT Structure of Django. As per Django Documentation, A view function 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, a redirect, a 404 error, an XML document, an ima
6 min read
Django Function Based Views
Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks. Django is based on MVT (Model View Template) architecture and revolves around CRUD (Create, Retrieve, Up
7 min read
Django Class Based Views
Class-Based Views (CBVs) allow developers to handle HTTP requests in a structured and reusable way. With CBVs, different HTTP methods (like GET, POST) are handled as separate methods in a class, which helps with code organization and reusability.Advantages of CBVsSeparation of Logic: CBVs separate d
6 min read
Class Based vs Function Based Views - Which One is Better to Use in Django?
Django, a powerful Python web framework, has become one of the most popular choices for web development due to its simplicity, scalability and versatility. One of the key features of Django is its ability to handle views and these views can be implemented using either Class-Based Views (CBVs) or Fun
6 min read
Django Templates
Templates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the ba
7 min read
Django Static File
Static Files such as Images, CSS, or JS files are often loaded via a different app in production websites to avoid loading multiple stuff from the same server. This article revolves around, how you can set up the static app in Django and server Static Files from the same.Create and Activate the Virt
3 min read
Django Forms
Django Forms
Django Forms are used to gather input from users, validate that input, and process it, often saving the data to the database. For example, when registering a user, a form collects information like name, email, and password.Django automatically maps form fields to corresponding HTML input elements. I
5 min read
How to Create a form using Django Forms
This article explains how to create a basic form using various form fields and attributes. Creating a form in Django is very similar to creating a model, you define the fields you want and specify their types. For example, a registration form might need fields like First Name (CharField), Roll Numbe
2 min read
Django Form | Data Types and Fields
When collecting user input in Django, forms play a crucial role in validating and processing the data before saving it to the database. Django provides a rich set of built-in form field types that correspond to different kinds of input, making it easy to build complex forms quickly.Each form field t
4 min read
Django Form | Build in Fields Argument
We utilize Django Forms to collect user data to put in a database. For various purposes, Django provides a range of model field forms with various field patterns. The most important characteristic of Django forms is their ability to handle the foundations of form construction in only a few lines of
3 min read
Python | Form validation using django
Prerequisites: Django Installation | Introduction to DjangoDjango works on an MVT pattern. So there is a need to create data models (or tables). For every table, a model class is created. Suppose there is a form that takes Username, gender, and text as input from the user, the task is to validate th
5 min read
Render Django Form Fields Manually
Django form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). We have already covered on How to create and use a form in Django?. A form comes with 3 in-built methods that can be used to ren
5 min read
Django Admin Interface - Python
Prerequisites: Django Introduction and Installation Creating a ProjectThe Django Admin Interface is one of the most powerful features of the Django framework. It provides a ready-to-use interface for managing project data through models, allowing developers and site administrators to perform Create,
3 min read
More topics on Django
Handling Ajax request in Django
AJAX (Asynchronous JavaScript and XML) is a web development technique that allows a web page to communicate with the server without reloading the entire page. In Django, AJAX is commonly used to enhance user experience by sending and receiving data in the background using JavaScript (or libraries li
3 min read
User Groups with Custom Permissions in Django - Python
Our task is to design the backend efficiently following the DRY (Don't Repeat Yourself) principle, by grouping users and assigning permissions accordingly. Users inherit the permissions of their groups.Let's consider a trip booking service, how they work with different plans and packages. There is a
4 min read
Django Admin Interface - Python
Prerequisites: Django Introduction and Installation Creating a ProjectThe Django Admin Interface is one of the most powerful features of the Django framework. It provides a ready-to-use interface for managing project data through models, allowing developers and site administrators to perform Create,
3 min read
Extending and customizing django-allauth in Python
Django-allauth is a powerful Django package that simplifies user authentication, registration, account management, and integration with social platforms like Google, Facebook, etc. It builds on Djangoâs built-in authentication system, providing a full suite of ready-to-use views and forms.Prerequisi
4 min read
Django - Dealing with Unapplied Migration Warnings
Django is a powerful web framework that provides a clean, reusable architecture to build robust applications quickly. It embraces the DRY (Don't Repeat Yourself) principle, allowing developers to write minimal, efficient code.Create and setup a Django project:Prerequisite: Django - Creating projectA
2 min read
Sessions framework using django - Python
Django sessions let us store data for each user across different pages, even if theyâre not logged in. The data is saved on the server and a small cookie (sessionid) is used to keep track of the user.A session stores information about a site visitor for the duration of their visit (and optionally be
3 min read
Django Sign Up and login with confirmation Email | Python
Django provides a built-in authentication system that handles users, login, logout, and registration. In this article, we will implement a user registration and login system with email confirmation using Django and django-crispy-forms for elegant form rendering.Install crispy forms using the termina
7 min read