Django templates help you manage your web application’s HTML. Templates use a mini-language with variables, tags, and filters. You can conditionally include blocks, create loops, and modify variables before they’re shown. Django comes with many built-in tags and filters, but what if they’re not enough? In that case, write your own! This tutorial covers the ins and outs of writing your own Django template custom tags and filters.
In this tutorial, you’ll learn how to:
- Write and register a function as a custom filter
- Understand how autoescaping works in custom tags and filters
- Use
@simple_tag
to write a custom template tag - Use
@inclusion_tag
to render a tag based on a subtemplate - Write a complex template tag with a parser and renderer
By the end of the tutorial, you’ll be able to write custom filters to modify data in your templates and custom tags that give you access to the full power of Python within your templates.
Free Bonus: Click here to get access to a free Django Learning Resources Guide (PDF) that shows you tips and tricks as well as common pitfalls to avoid when building Python + Django web applications.
Getting Started
To play around with your own Django template custom tags and filters, you’re going to need a Django project. You’ll build dinosoar, a small website with all sorts of dinosaur info. Although the name implies that you’ll only include flying dinos, that’s just for marketing spin. All your favorite heavyweights will be there as well.
If you’ve never set up a Django project before or if you need a refresher, you may want to read Get Started With Django Part 1: Build a Portfolio App first.
Django is a third-party library, so it should be installed in a virtual environment. If you’re new to virtual environments, check out Python Virtual Environments: A Primer. Create and activate a new virtual environment for yourself and then run the following commands:
1$ python -m pip install django==3.2.5
2$ django-admin startproject dinosoar
3$ cd dinosoar
4$ python manage.py startapp dinofacts
5$ python manage.py migrate
These commands perform the following actions:
- Line 1 runs the
pip
command to install Django. - Line 2 creates your new Django project.
- Line 3 changes the current working directory to the
dinosoar
project. - Line 4 uses the
manage.py
command to create a Django app calleddinofacts
, where your main view will live. - Line 5 migrates any database changes. Even if you aren’t creating models, this line is necessary because the Django admin is active by default.
With the project created, it’s time to make some configuration changes and write a quick view to help you test your custom tags and filters.
Setting Up a Django Project
You need to make some changes to your project’s settings to make Django aware of your newly created app and to configure your templates. Edit dinosoar/dinosoar/settings.py
and add dinofacts
to the INSTALLED_APPS
list:
34# dinosoar/dinosoar/settings.py
35
36INSTALLED_APPS = [
37 "django.contrib.admin",
38 "django.contrib.auth",
39 "django.contrib.contenttypes",
40 "django.contrib.sessions",
41 "django.contrib.messages",
42 "django.contrib.staticfiles",
43 "dinofacts",
44]
Within the same file, you’ll need to update the DIR
value in the TEMPLATES
attribute. This tells Django where to look for your template files:
57# dinosoar/dinosoar/settings.py
58
59TEMPLATES = [
60 {
61 "BACKEND": "django.template.backends.django.DjangoTemplates",
62 "DIRS": [
63 BASE_DIR / "templates",
64 ],
65 "APP_DIRS": True,
66 "OPTIONS": {
67 "context_processors": [
68 "django.template.context_processors.debug",
69 "django.template.context_processors.request",
70 "django.contrib.auth.context_processors.auth",
71 "django.contrib.messages.context_processors.messages",
72 ],
73 },
Starting with Django 3.1, the BASE_DIR
value that specifies where the project lives is a pathlib
object. The change to the DIRS
value above tells Django to look in a templates/
subdirectory within your project directory.
Note: If you use Django 3.0 or earlier, you’ll set BASE_DIR
using the os.path
module. In that case, use os.path.join()
to specify the path.
With the settings changed, don’t forget to create the templates/
directory within your project:
$ pwd
/home/realpython/dinosoar
$ mkdir templates
It’s time to start writing some code. To test your custom template tags and filters, you’ll need a view. Edit dinosoar/dinofacts/views.py
as follows:
1# dinosoar/dinofacts/views.py
2
3from datetime import datetime
4from django.shortcuts import render
5
6def show_dino(request, name):
7 data = {
8 "dinosaurs": [
9 "Tyrannosaurus",
10 "Stegosaurus",
11 "Raptor",
12 "Triceratops",
13 ],
14 "now": datetime.now(),
15 }
16
17 return render(request, name + ".html", data)
Lines 7 to 15 create a dictionary with some sample data. You’ll use this in your templates to test your tags and filters. The rest of this view does something a little unorthodox: it takes a parameter that specifies the name of a template.
Read the full article at https://realpython.com/django-template-custom-tags-filters/ »
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]
from Planet Python
via read more
No comments:
Post a Comment