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
templatesdirectory in your app or project. - In your view function, use
render(request, 'template_name.html', context)to load and display the template. - The
contextis 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
templatesfolder in the correct location or not configuringTEMPLATESinsettings.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
| Step | Description |
|---|---|
| Create templates folder | Place HTML files inside a folder named 'templates' in your app or project. |
| Write HTML with Django tags | Use {{ variable }} to insert dynamic data. |
| Render template in view | Use render(request, 'template.html', context) to display the template. |
| Configure settings | Ensure '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.