Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Web Development with Django

You're reading from  Web Development with Django

Product type Book
Published in Feb 2021
Publisher Packt
ISBN-13 9781839212505
Pages 826 pages
Edition 1st Edition
Languages
Authors (5):
Ben Shaw Ben Shaw
Profile icon Ben Shaw
Saurabh Badhwar Saurabh Badhwar
Profile icon Saurabh Badhwar
Andrew Bird Andrew Bird
Profile icon Andrew Bird
Bharath Chandra K S Bharath Chandra K S
Profile icon Bharath Chandra K S
Chris Guest Chris Guest
Profile icon Chris Guest
View More author details

Table of Contents (17) Chapters

Preface
1. Introduction to Django 2. Models and Migrations 3. URL Mapping, Views, and Templates 4. Introduction to Django Admin 5. Serving Static Files 6. Forms 7. Advanced Form Validation and Model Forms 8. Media Serving and File Uploads 9. Sessions and Authentication 10. Advanced Django Admin and Customizations 11. Advanced Templating and Class-Based Views 12. Building a REST API 13. Generating CSV, PDF, and Other Binary Files 14. Testing 15. Django Third-Party Libraries 16. Using a Frontend JavaScript Library with Django

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 2021 Publisher: Packt ISBN-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.
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}