Django Templates Basics: A Complete Guide for Beginners
Hello, everyone! Today we're going to learn the basics of Django Templates. Djangoto get started with web development? Or maybe you're thinking about getting started? Whatever the case, Django Templates is an important part of your toolkit to know. It may seem daunting at first, but don't worry! In this post, we'll make learning the basics of Django Templates easy and fun.
What are Django Templates?

Django Templates use the Tools to dynamically generate HTML pagesin the Django framework, which is used by the Representation (view) part of the page. More than just HTML documents, templates combine information pulled from a database or dynamic data to deliver personalized content to users. This allows you to Bridging the gap between frontend and backend role, and is a great contributor to reusability and maintainability.
Key Features
- Dynamic data representation
- You can use the template language to represent Python data (strings, lists, objects, etc.) in HTML pages.
- Example: Displaying a list of user names or products pulled from a database on a page.
- Template languages
- Django has its own Template tags and filtersin the file.
- You can incorporate basic programming constructs like conditional statements, loops, and more into your HTML.
- Example:
{% if user.is_authenticated %} <p>Welcome, {{ user.username }}!</p> {% else %} <p>Please log in.</p> {% endif %}
- Reusable components
- Templates are created using the
includeandextendsto reuse common elements (e.g., headers, footers) across multiple pages. - Example: Creating a basic layout template that is common to all pages.
- Templates are created using the
- Client-server collaboration
- The server prepares the data, uses the template to generate the final HTML, and delivers it to the client (browser).
- This allows clients to receive simple HTML rendering results without complicated logic.
The role of Django Templates
- Web page blueprints: By separating data and logic, developers can intuitively organize the content and design of a page.
- Increase front-end-back-end collaboration: Backend developers can focus on data and business logic, while frontend developers can focus more on design and user experience with templates.
Django Templates Basics: Creating the Basic Structure
First, create a 'templates' folder in your project directory with a structure similar to the one below.
myproject/
├── myapp/
├── myproject/
├── templates/
└── manage.pyAnd the settings.py file, you'll need to add the templates directory. 'DIRS': [BASE_DIR / 'templates'], (A lot of people make a mistake here, so be sure to use the Comma ( , ) ).
TEMPLATES = [
{ 'BACKEND'
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
...
},
]Create your first Template
Now, the templates Inside the folder home.html file. The example below is no different than a regular HTML file, and is intended to teach you the basics of Django Templates.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>My Django Site</title>
</head>
<body>
<h1>Hello, and welcome to the world of Django!</h1>
<p>This is my first Django template.</p>
</body>
</html>Using Templates
To use a template, you must use the render function in the view. views.py Try writing something like this in your file The lines with # are comments, so just note them.
# Imports the render function from Django's shortcuts module.
The # render function is used to render the specified template file and return an HTTP response.
from django.shortcuts import render
# View function definition: home
# This function is called to respond to a URL request.
# - request: An HttpRequest object that is automatically passed by Django, containing the user's request information.
def home(request):
# render function:
# - First argument: Pass in the request object.
# - Second argument: Specifies the name of the template file to render ('home.html').
# - Third argument (optional): You can pass an additional data (Context) dictionary to pass to the template.
# - Return value: Returns an HttpResponse object containing the rendered HTML.
return render(request, 'home.html')
Passing data to a template
You can pass data from a view to a template.
# home view function definition
This view function is called when a # user accesses a specific URL.
def home(request):
# create context dictionary
# - Define the data to pass to the template.
# - Here we have assigned the value 'withdrawal' to the 'name' key.
# - In the template, you can access the data as {{ name }}.
context = {'name': 'withdrawal'}
return render(request, 'home.html', context)
And you can use this data in your template
# {{ }} is a variable expression used by the Django template language.
# It references the value of the name key of the context dictionary passed in the view function.
# Example: If passed as context = {'name': 'withdraw'} in a view function, {{ name }} will be replaced with 'withdraw'.
<h1>Hello, {{ name }}!</h1>Using the Template tag

The Django Templates language uses the Template tagsand Variable expressionsfor the tag. We'll explain the various tags one by one.
1. {% if ... %} / {% else %} / {% endif %}
- Conditional statement tagswhich allows you to branch HTML content based on specific conditions.
iftag and write the conditional expression inside the tag,elseis the part that is executed when the condition is not met.endifto end the conditional statement.
Example code
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
{% else %}
<p>Please sign in.</p>
{% endif %}How it works
user.is_authenticated:- The user object provided by Django (
user), which returns whether the user is authenticated.
- The user object provided by Django (
- Based on conditions:
- If the user is logged in:
<p>Welcome, [username]!</p>Output. - If you're not logged in:
<p>Please sign in.</p>Output.
- If the user is logged in:
2. {% for ... in ... %} / {% endfor %}
- Repeat Statement Tagsto dynamically generate HTML content by traversing iterable objects like lists or queriesets.
fortag, specifying the objects to be repeated,endforto end the loop.
Example code
{% for item in items %}
- {{ item }}
{% endfor %}
How it works
itemscontextA list or queryset passed in from a dictionary.
- Iterative processing
itemsEach element in theitem) toInsert it inside a tag to output it.
- For example,
context = {'items': ['apple', 'banana', 'cherry']}if:- Apple
- Banana
- Cherry
3. {{ ... }} (variable expression)
- A variable expression is a
contextis responsible for outputting the data passed to it. - Braces (
{{ }}) inside the variable name to display its value in the template.
Example code
<p>Welcome, {{ user.username }}!</p>How it works
user.usernamecontextpassed in theuserobject'susernameOutputs the properties.
- For example,
user.username = 'withdraw'if:<p>Welcome, Chulsoo!</p>
Tag summaries and additional descriptions
| Tags | Description. | Example |
|---|---|---|
{% if ... %} | Display content based on conditions. | {% if user.is_authenticated %} |
{% else %} | Fires when a condition is not met. | {% else %} |
{% endif %} | Exit the conditional statement. | {% endif %} |
{% for ... in ... %} | Generate content by traversing iterable objects, such as lists and query sets. | {% for item in items %} ... {% endfor %} |
{{ ... }} | As a variable expression, contextoutputs the data passed to it. | {{ user.username }} |
{% include ... %} | You can reuse common elements by inserting other template files. | {% include 'header.html' %} |
{% extends ... %} | Extend the current template based on another template. | {% extends 'base.html' %} |
{% block ... %} | Define or override specific parts of an expanded template. | {% block content %} ... {% endblock %} |
Advantages of the Django template language
- Separate code and design: Separates HTML and Python code to make it easier to maintain.
- Intuitive grammar: Provides an intuitive syntax that Python developers can easily pick up.
- Create dynamic content: Flexibly process data with iterations and conditional statements to deliver personalized content.
- Reusability:
include,extends,blocktags to maximize template reusability.
Using the Template filter

Django template filters use the Modify or transform the output of a variableis a tool used to Pipes (|) symbol to apply to variables, and allows for simple and intuitive manipulation of data in templates.
Example description
djangoCopyEditTitle: {{ title|upper }}
Content: {{ content|truncatewords:30 }}
{{ title|upper }}:titlevariable to a string in the All capsto a new file.- Example:
title = "Hello World"then the result isHELLO WORLD.
{{ content|truncatewords:30 }}:contentString in variable by word Trim to a maximum of 30 words.- Useful for summarizing long text or limiting display space.
- Example:
content = "This is a long text with many words..."then the result isThis is a long text with....
Working with static files

To work with static files like CSS, JavaScript, and images {% load static %} tag:
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<img src="{% static 'images/logo.png' %}" alt="로고">Handling URLs
Instead of hardcoding the URL in the template, you can use the {% url %} Use tags:
<a href="/en/{% url 'home' %}/">To Home</a>This way, you don't have to modify your template if your URL settings change.
Finalize
That's it for the basics of Django templates. Templates make it easy to create dynamic and flexible web pages. The next step is to learn template inheritance, which allows you to reduce code duplication and better organize the structure of your website.
Django templates may seem complicated at first, but with a little practice, you'll get the hang of them in no time. Keep practicing and explore the different features of templates. Good luck!
For reference, if you want to see Django's core features in their entirety, Mastering the Django MTV Pattern: A Complete Guide to Models, Views, Templates, and Forms Check out the post.







