Wednesday, September 22, 2021

Real Python: The Django Template Language: Tags and Filters

Django is a powerful framework for creating web applications in Python. Its features include database models, routing URLs, authentication, user management, administrative tools, and a template language. You can compose reusable HTML that changes based on the data you pass to the template language. Django templates use tags and filters to define a mini-language that’s similar to Python—but isn’t Python.

You’ll get to know Django templates through the tags and filters you use to compose reusable HTML.

In this tutorial, you’ll learn how to:

  • Write, compile, and render a Django template
  • Use the render() shortcut in views to quickly use templates
  • Use template tags for conditionals and loops in your templates
  • Create reusable templates with inheritance and inclusion
  • Modify the presentation of your data through template filters

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.

Creating a Django Project

To experiment with Django templates, you’re going to need a project so that you can play around with the code. You’ll be building MoviePalace: the world’s smallest, simplest movie website. For a more detailed example of starting a new project, you can read Get Started With Django Part 1: Build a Portfolio App.

Django isn’t part of the standard Python library, so you’ll first need to install it. When dealing with third-party libraries, you should use a virtual environment. For a refresher on virtual environments, you can read over Python Virtual Environments: A Primer.

Once you have a virtual environment, run the following commands to get going:

 1$ python -m pip install django==3.2.5
 2$ django-admin startproject MoviePalace
 3$ cd MoviePalace
 4$ python manage.py startapp core

Line 1 installs Django into your virtual environment using pip. On line 2, the django-admin command creates a new Django project called MoviePalace. A Django project is comprised of apps, where your code lives. The fourth command creates an app named core.

You’re almost ready to go. The last step is to tell Django about your newly created core app. You do this by editing the MoviePalace/settings.py file and adding "core" to the list of INSTALLED_APPS:

33INSTALLED_APPS = [
34    "django.contrib.admin",
35    "django.contrib.auth",
36    "django.contrib.contenttypes",
37    "django.contrib.sessions",
38    "django.contrib.messages",
39    "django.contrib.staticfiles",
40    "core",
41]

With core registered as an app, you can now write a view containing a template.

Getting Ready to Use Django Templates

Django was created at a newspaper to help build web applications quickly. One of the goals of the framework was to separate the concerns of the business logic from the presentation logic.

Web designers, rather than Python programmers, frequently did the HTML development at the paper. Because of this, the developers decided not to allow the execution of Python within the template language. This decision simplified what the designers needed to know and sandboxed their code for security reasons. The end result was a separate mini-language. This approach is in contrast to the PHP approach, where the code is directly embedded in the HTML.

Compiling and Rendering Django Templates

Django templates let you dynamically change output content within a rendering context. You can think of templates as a form letter, where the letter’s contents include places where information can be inserted. You can run the rendering process multiple times with different data and get different results each time.

Django provides the Template and Context classes to represent the string template being rendered and the data being used during generation. The Context class is a wrapper to a dict and provides key-value pairs to populate the generated content. The result of a rendered template can be any text but is frequently HTML. Django is a web framework, after all.

It’s time to build your first template. To see one in action, you’ll first need a view. Add the following code to core/views.py:

 1# core/views.py
 2from django.http import HttpResponse
 3from django.template import Context, Template
 4
 5def citizen_kane(request):
 6    content = """ was released in """
 7    template = Template(content)
 8    context = Context({"movie": "Citizen Kane", "year": 1941})
 9
10    result = template.render(context)
11    return HttpResponse(result)

In this view, you see some of the main concepts that make up the Django templating language:

  • Line 6 contains references to movie and year. This is similar to a Python f-string. The double braces, or mustache brackets, indicate the items that Django replaces when it renders the template.
  • Line 7 instantiates a Template object by passing in the string that specifies the template.
  • Line 8 creates a Context object by populating it with a dictionary. The Context object contains all of the data available to the template when Django renders it. The template contains two items to replace: with "Citizen Kane" and with 1941.
  • Line 10 has the call to the .render() method that generates the result.
  • Line 11 returns the rendered content wrapped in an HttpResponse object.

To test this out, you’ll need to make this view available in the browser, so you’ll need to add a route. Modify MoviePalace/urls.py as follows:

Read the full article at https://realpython.com/django-templates-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

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...