0% found this document useful (0 votes)
8 views22 pages

4 - Django Forms Model Forms

The document explains Django Forms and Model Forms, which are essential for handling user input in web applications. It details how to create, validate, and render forms in Django, emphasizing the importance of security and data handling. Additionally, it covers how to build Model Forms from Django models, allowing for easy data saving and management in the database.

Uploaded by

Waqas Sharif
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views22 pages

4 - Django Forms Model Forms

The document explains Django Forms and Model Forms, which are essential for handling user input in web applications. It details how to create, validate, and render forms in Django, emphasizing the importance of security and data handling. Additionally, it covers how to build Model Forms from Django models, allowing for easy data saving and management in the database.

Uploaded by

Waqas Sharif
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Django Form

&
Model Form

1
What is a form?

Forms are the most generic way of accepting


input from the sites users. A form is a set of
HTML input elements enclosed in the
<form>...</form> tags. An HTML form submits
the data using either GET or POST HTTP methods
and the data is of the form of key-value pairs.
These values can be accessed from the request
object's GET/POST attributes in the view.

2
Form being the most common way of input on
the Web, any sensible web-framework must
provide sophisticated ways of handling form
inputs. Form inputs also pose most of the
security threats a web application can face.
Hence it is essential to understand how to
properly handle form inputs on any framework.

3
The Django's Forms

The Django's Form class gives a logical representation of an


HTML form, defines how it should behave and how it appears in
the HTML.
Before we start working with the Form class of Django, let us
build a basic HTML form - a user login form with just two input
fields. The form in HTML will look like this

Each attribute of model represent a database field

ANY
QUESTION?

5
There are few things to notice. The above form has two inputs -
a text field named username (the name attribute in the html in
put field is what determines the name of input field) and a pass
word field named password - and a submit button.

The form uses POST method to submit form data to server. The
action attribute of the form determines the url to which the for
m data has to be submitted.
ANY
QUESTION?

6
To handle this data on the server-side we define a form as
follows.

Each attribute of model represent a database field

ANY
QUESTION?
Though the password input in the html is of password type
in the html, it is just text and must be processed as a
CharField

7
Initializing forms in views

Once a form is submitted to a view, we create the form object


from the POST data (or GET) as follows:

Each attribute of model represent a database field

ANY
QUESTION?

8
Observe that the fieldnames in the form are same as the name
of the input fields of the HTML forms. This lets us directly
initialize the form with the request.POST dictionary (otherwise
we need to create a dictionary that maps form field names to
the HTML input names).
Each attribute of model represent a database field

ANY
QUESTION?

9
Validation of data with forms

Creating form object looks fancier but what advantage does


that give us? The first advantage that the Forms provide us is
the validation of input. Input validation is extremely important
in terms of security of web applications.

Form data can be validated using the is_valid() method. The


method returns True if the data is valid and False otherwise.
ANY
In our example, we have defined our login form with two fields
each with argument max_length set to 20.
QUESTION?

10
When we execute the is_valid() method of the form, the form
checks that the each field’s value length is less than 20. If
any of the field value is greater than 20, the method returns
false. Once the is_valid() method is called and the data is
valid, the data is made available as cleaned_data attribute of
the class.

11
Based on the is_valid() method our login view will develop
like this.

Each attribute of model represent a database field

12
Rendering Forms as HTML

The another advantage that forms provide is handling the


appearance of HTML forms. Earlier we have created a login
form in HTML. In practice we do not to write any of that
HTML. All we need to do is to use the form in our templates
with {{ form
Each }}, andofjinja
attribute model(Django's templating
represent a database field engine) will
take care of generating all the HTML necessary.

13
Our template rendering the form will look like this:

Each attribute of model represent a database field

14
This renders in the template as

Each attribute of model represent a database field

15
Model forms

Most of the times our user inputs are very close to our
models, after all the input data is stored in models. Django
provides us with Model Forms, the forms that can be built
from models.

Building a Each
form from of
attribute a model
model is really
represent easy.field
a database We just need to
extend the django.forms.ModelForm class, specify the model
(that we want to built the form from) in the Meta class and
specify the fields to include.

16
We will first define a model before building our model form.
Here is our model.

Each attribute of model represent a database field

17
Now, we define our model form like:

18
The form's model Meta attribute specifies the model to use to
build the form and the fields attribute specifies the fields that
need to be included in the form. The fields attribute takes a
list (or a tuple) of model field names. The special string
'__all__' specifies that all the fields in the model needs to be
Each attribute of model represent a database field
included.

We can also specify only the fields that need to be excluded


with exclude attribute which will be a list (or a tuple) of field
names that should be excluded. Only one of fields and exclude
attributes can be used in model form.

19
Saving model forms in to database

Model forms provide a close binding of forms to the models and


allow us to save the data into model directly with the save()
method. In our example of AuthorForm model form, once the
data is validated with the is_valid() method we can use the
form.save()Each
method tomodel
attribute of create a model
represent instance
a database field (saved to
database). The method will return a model instance if it is
successful.

ANY
QUESTION?

20
Using the model form AuthorForm to create a model instance
of Author, our view would look like this.

21
The save() method creates a model instance and saves it to
the database. We are, of course, allowed to override the
save() method to create the model instance that suits our
requirement. In another blog post, I will explore more on how
to validate form data, adding custom validators, control the
redered HTML format with widgets etc.

22

You might also like