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

6. Forms

Overview

This chapter introduces web forms, a method of sending information from the browser to the web server. It starts with an introduction to forms in general and discusses how data is encoded to be sent to the server. You will learn about the differences between sending form data in a GET HTTP request and sending it in a POST HTTP request, and how to choose which one to use. By the end of the chapter, you will know how Django's form library is used to build and validate forms automatically and how it cuts down the amount of manual HTML you need to write.

Introduction

So far, the views we have been building for Django have been one-way only. Our browser is retrieving data from the views we have written but it does not send any data back to them. In Chapter 4, Introduction to Django Admin, we created model instances using the Django admin and submitting forms, but those were using views built into Django, not created by us. In this chapter, we will use the Django Forms library to start accepting user-submitted data. The data will be provided through GET requests in the URL parameters, and/or POST requests in the body of the request. But before we get into the details, first let us understand what are forms in Django.

What Is a Form?

When working with an interactive web app, we not only want to provide data to users but also accept data from them to either customize the responses we are generating or let them submit data to the site. When browsing the web, you will most definitely have used forms. Whether you're logging in to your internet banking account, surfing the web with a browser, posting a message on social media, or writing an email in an online email client, in all these cases, you are entering data in a form. A form is made up of inputs that define key-value pairs of data to submit to the server. For example, when logging in to a website, the data being sent would have the keys username and password, with the values of your username and your password, respectively. We will go into the different types of inputs in more detail in the Types of Inputs section. Each input in the form has a name, and this is how its data is identified on the server-side (in a Django view). There can be...

The Django Forms Library

We've looked at how to manually write forms in HTML and how to access the data on the request object using QueryDict. We saw that the browser provides some validation for us for certain field types, such as email or numbers, but we have not tried validating the data in the Python view. We should validate the form in the Python view for two reasons:

  • It is not safe to rely solely on browser-based validation of input data. A browser may not implement certain validation features, meaning the user could post any type of data. For example, older browsers don't validate number fields, so a user can type in a number outside the range we are expecting. Furthermore, a malicious user could try to send harmful data without using a browser at all. The browser validation should be considered as a nicety for the user and that's all.
  • The browser does not allow us to do cross-field validation. For example, we can use the required attribute for inputs...

Validating Forms and Retrieving Python Values

So far, we have seen how Django Forms makes it much simpler to define a form using Python code and have it automatically rendered. We will now look at the other part of what makes Django forms useful: their ability to automatically validate the form and then retrieve native Python objects and values from them.

In Django, a form can either be unbound or bound. These terms describe whether or not the form has had the submitted POST data sent to it for validation. So far, we have only seen unbound forms – they are instantiated without arguments, like this:

form = ExampleForm()

A form is bound if it is called with some data to be used for validation, such as the POST data. A bound form can be created like this:

form = ExampleForm(request.POST)

A bound form allows us to start using built-in validation-related tools: first, the is_valid method to check the form's validity, then the cleaned_data attribute on the...

Summary

This chapter was an introduction to forms in Django. We introduced some HTML inputs for entering data onto a web page. We talked about how data is submitted to a web application and when to use GET and POST requests. We then looked at how Django's form classes can make generating the form HTML simpler, as well as allowing the automatic building of forms using models. We enhanced Bookr some more by building the book search functionality.

In the next chapter, we will go deeper into forms and learn how to customize the display of form fields, how to add more advanced validation to your form, and how to automatically save model instances by using the ModelForm class.

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