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

7. Advanced Form Validation and Model Forms

Overview

Continuing your journey with the Bookr application, you will begin this chapter by adding a new form to your app with custom multi-field validation and form cleaning. You will learn how to set the initial values on your form and customize the widgets (the HTML input elements that are being generated). Then you will be introduced to the ModelForm class, which allows a form to be automatically created from a model. You will use it in a view to automatically save the new or changed Model instance.

By the end of this chapter, you will know how to add extra multi-field validation to Django forms, how to customize and set form widgets for fields, how to use ModelForms to automatically create a form from a Django model, and how to automatically create Model instances from ModelForms.

Introduction

This chapter builds upon the knowledge we gained in Chapter 6, Forms, where we learned how to submit data from an HTML form to a Django view, both with a manually built HTML form and with a Django form. We used Django's form library to build and automatically validate forms with basic validation. For example, now we can build forms that check whether a date is entered in its desired format, whether a number is input where a user must enter their age, and whether a dropdown is selected before the user clicks the Submit button. However, most large-scale websites require validation that is a bit more advanced.

For instance, a certain field might only be required if another field is set. Let's say we want to add a checkbox to allow users to sign up for our monthly newsletter. It has a textbox below it that lets them enter their email address. With some basic validation, we can check whether:

  • The user has checked the checkbox.
  • The user has entered their...

Custom Field Validation and Cleaning

We have seen how a Django form converts values from an HTTP request, which are strings, into Python objects. In a non-custom Django form, the target type is dependent on the field class. For example, the Python type derived from IntegerField is int, and string values are given to us verbatim, as the user entered them. But we can also implement methods on our Form class to alter the output values from our fields in any way we choose. The allows us to clean or filter the user's input data to fit what we expect better. We could round an integer to the nearest multiple of ten to fit into a batch size for ordering specific items. Or we could transform an email address to lowercase so that the data is consistent for searching.

We can also implement some custom validators. We will look at a couple of different ways of validating fields: by writing a custom validator, and by writing a custom clean method for the field. Each method has its pros and...

Summary

This chapter was a deep dive into forms. We saw how to enhance Django forms with custom validation advanced rules for cleaning data and validating fields. We saw how custom cleaning methods can transform the data that we get out of forms. A nice feature we saw that can be added to forms is the ability to set initial and placeholder values on fields, so the user does not have to fill them out.

We then looked at how to use the ModelForm class to automatically create a form from a Django model. We saw how to only show some fields to the user and how to apply custom form validation rules to the ModelForm. We also saw how Django can automatically save the new or updated model instance to the database inside the view. In the activities for this chapter, we enhanced Bookr some more by adding forms for creating and editing publishers and submitting reviews. The next chapter will carry on the theme of submitting user input, and along with that, we'll discuss how Django handles...

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 €14.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