Reader small image

You're reading from  Web Development with Django

Product typeBook
Published inFeb 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781839212505
Edition1st Edition
Languages
Tools
Right arrow
Authors (5):
Ben Shaw
Ben Shaw
author image
Ben Shaw

Ben Shaw is a software engineer based in Auckland, New Zealand. He has worked as a developer for over 14 years and has been building websites with Django since 2007. In that time, his experience has helped many different types of companies, ranging in size from start-ups to large enterprises. He is also interested in machine learning, data science, automating deployments, and DevOps. When not programming, Ben enjoys outdoor sports and spending time with his partner and son.
Read more about Ben Shaw

Saurabh Badhwar
Saurabh Badhwar
author image
Saurabh Badhwar

Saurabh Badhwar is an infrastructure engineer who works on building tools and frameworks that enhance developer productivity. A major part of his work involves using Python to develop services that scale to thousands of concurrent users. He is currently employed at LinkedIn and works on infrastructure performance tools and services.
Read more about Saurabh Badhwar

Andrew Bird
Andrew Bird
author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

Bharath Chandra K S
Bharath Chandra K S
author image
Bharath Chandra K S

Bharath Chandra K S lives in Sydney, Australia, and has over 14 years of software industry experience. He is very passionate about software development on the Python stack, including frameworks such as Flask and Django. He has experience working with both monolithic and microservice architectures and has built various public-facing applications and data processing backend systems. When not cooking up software applications, he likes to cook some nice food.
Read more about Bharath Chandra K S

Chris Guest
Chris Guest
author image
Chris Guest

Chris Guest is based in Melbourne and started programming in Python 24 years ago, when it was an obscure academic language. He has since used his Python knowledge in the publishing, hospitality, medical, academic and financial sectors. Throughout his career, he has worked with many Python web development frameworks, including Zope, TurboGears, web2py, and Flask, although he still prefers Django.
Read more about Chris Guest

View More author details
Right arrow

11. Advanced Templating and Class-Based Views

Overview

In this chapter, you will learn how to use Django's templating API to create custom template tags and filters. You will also write class-based views that will help you perform CRUD operations. By the end of this chapter, you will have a clear understanding of how Django handles advanced templating and how you can build custom views that support CRUD-based operations. You will be able to use classes to define views inside Django and be able to build custom tags and filters to complement the powerful templating engine provided by Django.

Introduction

In Chapter 3, URL Mapping, Views, and Templates, we learned how to build views and create templates in Django. Then, we learned how to use those views to render the templates we built. In this chapter, we will build upon our knowledge of developing views by using class-based views, which allow us to write views that can group logical methods into a single entity. This skill comes in handy when developing a view that maps to multiple HTTP request methods for the same Application Programming Interface (API) endpoint. With method-based views, we may end up using a lot of if-else conditions to successfully handle the different types of HTTP request methods. In contrast, class-based views allow us to define separate methods for every HTTP request method we want to handle. Then, based on the type of request received, Django takes care of calling the correct method in the class-based view.

Beyond the ability to build views based on different development techniques, Django...

Template Filters

While developing templates, developers often just want to change the value of a template variable before rendering it to the user. For example, consider that we are building a profile page for a Bookr user. There, we want to show the number of books the user has read. Below that, we also want to show a table listing the books they have read.

To achieve this, we can pass two separate variables from our view to the HTML template. One can be named books_read, which denotes the number of books read by the user. The other can be book_list, containing the list of names of the books read by the user, for example:

<span class="books_read">You have read {{ books_read }} books</span>
<ul>
{% for book in book_list %}
<li>{{ book }} </li>
{% endfor %}
</ul>

Or we can use Template filters. Template filters in Django are simple Python-based functions that accept a variable as an argument (and any additional data in the context...

Custom Template Filters

Django supplies a lot of useful filters that we can use in our templates while we are working on our projects. But what if someone wants to format a specific piece of text and render it with different fonts? Or say if someone wants to translate an error code to a user-friendly error message based on the mapping of the error code in the backend. In these cases, predefined filters do not suffice, and we would like to write our own filter that we can reuse across the project.

Luckily, Django supplies an easy-to-use API that we can use to write custom filters. This API provides developers with some useful decorator functions that can be used to quickly register a Python function as a custom template filter. Once a Python function is registered as a custom filter, a developer can start using the function in templates.

An instance of this template library method is required to access these filters. This instance can be created by instantiating the Library...

Template Tags

Template tags are a powerful feature of Django's templating engine. They allow developers to build powerful templates by generating HTML through the evaluation of certain conditions and help avoid the repetitive writing of common code.

One example where we may use template tags is the sign up/login options in the navigation bar of a website. In this case, we can use template tags to evaluate whether the visitor on the current page is logged in. Based on that, we can render either a profile banner or a sign up/login banner.

Tags are also a common occurrence while developing templates. For example, consider the following line of code, which we used to import the custom filters inside our templates in Exercise 11.01, Creating a Custom Template Filter:

{% load explode_filter %}

This uses a template tag known as load, which is responsible for loading the explode filter into the template. Template tags are much more powerful compared to filters. While filters...

Django Views

To recall, a view in Django is a piece of Python code that allows a request to be taken in, performs an action based on the request, and then returns a response to the user, and hence forms an important part of our Django applications.

Inside Django, we have the option of building our views by following two different methodologies, one of which we have already seen in the preceding examples and is known as function-based views, while the other one, which we will be covering soon, is known as class-based views:

  • Function-Based Views (FBVs): FBVs inside Django are nothing more than generic Python functions that are supposed to take an HTTPRequest type object as their first positional parameter and return an HTTPResponse type object, which corresponds to the action the view wants to perform once the request is processed by it. In the preceding exercise, index() and greeting_view() were examples of FBVs.
  • Class-Based Views (CBVs): CBVs are views that closely adhere...

Class-Based Views

Django provides different ways in which developers can write views for their applications. One way is to map a Python function to act as a view function to create FBVs. Another way of creating views is to use Python object instances (which are based on top of Python classes). These are known as CBVs. An important question that arises is, what is the need for a CBV when we can already create views using the FBV approach?

The idea here, when creating FBVs, is that at times, we may be replicating the same logic again and again, for example, the processing of certain fields, or logic for handling certain request types. Although it is completely possible to create logically separate functions that handle a particular piece of logic, the task becomes difficult to manage as the complexity of the application increases.

This is where CBVs come in handy, where they abstract away implementation of the common repetitive code that we need to write to handle certain tasks...

Summary

In this chapter, we learned about the advanced templating concepts in Django and understood how we can create custom template tags and filters to fit a myriad of use cases and support the reusability of components across the application. We then looked at how Django provides us with the flexibility to implement FBVs and CBVs to render our responses.

While exploring CBVs, we learned how they can help us avoid code duplication and how we can leverage the built-in CBVs to render forms that save data, help us update existing records, and implement CRUD operations on our database resources.

As we move to the next chapter, we will now utilize our knowledge of building CBVs to work on implementing REST APIs in Django. This will allow us to perform well-defined HTTP operations on our data inside our Bookr application without maintaining any state inside the application.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Web Development with Django
Published in: Feb 2021Publisher: PacktISBN-13: 9781839212505
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (5)

author image
Ben Shaw

Ben Shaw is a software engineer based in Auckland, New Zealand. He has worked as a developer for over 14 years and has been building websites with Django since 2007. In that time, his experience has helped many different types of companies, ranging in size from start-ups to large enterprises. He is also interested in machine learning, data science, automating deployments, and DevOps. When not programming, Ben enjoys outdoor sports and spending time with his partner and son.
Read more about Ben Shaw

author image
Saurabh Badhwar

Saurabh Badhwar is an infrastructure engineer who works on building tools and frameworks that enhance developer productivity. A major part of his work involves using Python to develop services that scale to thousands of concurrent users. He is currently employed at LinkedIn and works on infrastructure performance tools and services.
Read more about Saurabh Badhwar

author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

author image
Bharath Chandra K S

Bharath Chandra K S lives in Sydney, Australia, and has over 14 years of software industry experience. He is very passionate about software development on the Python stack, including frameworks such as Flask and Django. He has experience working with both monolithic and microservice architectures and has built various public-facing applications and data processing backend systems. When not cooking up software applications, he likes to cook some nice food.
Read more about Bharath Chandra K S

author image
Chris Guest

Chris Guest is based in Melbourne and started programming in Python 24 years ago, when it was an obscure academic language. He has since used his Python knowledge in the publishing, hospitality, medical, academic and financial sectors. Throughout his career, he has worked with many Python web development frameworks, including Zope, TurboGears, web2py, and Flask, although he still prefers Django.
Read more about Chris Guest