0
0
DjangoHow-ToBeginner · 3 min read

How to Create Template in Django: Simple Guide

In Django, create a template by making an HTML file inside a templates folder and then render it in a view using render(). Templates allow you to separate HTML from Python code and display dynamic content.
📐

Syntax

To create and use a template in Django, follow these steps:

  • Create an HTML file inside a templates directory in your app or project.
  • In your view function, use render(request, 'template_name.html', context) to load and display the template.
  • The context is a dictionary with data you want to show in the template.
python
from django.shortcuts import render

def my_view(request):
    context = {'name': 'Alice'}
    return render(request, 'hello.html', context)
💻

Example

This example shows how to create a simple template that greets a user by name.

python and html
# In views.py
from django.shortcuts import render

def greet(request):
    context = {'user_name': 'Alice'}
    return render(request, 'greet.html', context)

# In templates/greet.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Greeting</title>
</head>
<body>
    <h1>Hello, {{ user_name }}!</h1>
</body>
</html>
Output
<h1>Hello, Alice!</h1>
⚠️

Common Pitfalls

Common mistakes when creating templates in Django include:

  • Not placing the templates folder in the correct location or not configuring TEMPLATES in settings.py.
  • Forgetting to pass a context dictionary to the render() function.
  • Using incorrect template variable syntax (must use double curly braces {{ variable }}).
  • Not restarting the server after adding new templates (sometimes needed).
python
# Wrong: Missing context
return render(request, 'greet.html')

# Right: Pass context
return render(request, 'greet.html', {'user_name': 'Alice'})
📊

Quick Reference

StepDescription
Create templates folderPlace HTML files inside a folder named 'templates' in your app or project.
Write HTML with Django tagsUse {{ variable }} to insert dynamic data.
Render template in viewUse render(request, 'template.html', context) to display the template.
Configure settingsEnsure 'DIRS' in TEMPLATES setting includes your templates path if outside app folders.

Key Takeaways

Create HTML files inside a 'templates' folder to define Django templates.
Use the render() function in views to load templates with dynamic data.
Pass a context dictionary to templates to display variables.
Use {{ variable }} syntax inside templates to show data.
Check template folder location and settings if templates do not load.