Working With Django Forms

 

Django Forms:

1) It is the very important concept in web development.

2) The main purpose of forms is to take user input.

   Eg: login form, registration form, enquiry form etc

3) From the forms we can read end user provided input data and we can use that data

   based on requirement. We may store in the database for future purpose. We may use

   just for validation/authentication purpose etc

4) Here we have to use Django specific forms but not HTML forms.


Advantages of Django Forms over HTML Forms:

1) We can develop forms very easily with python code

2) We can generate HTML Form widgets/components (like textarea, email, pwd etc) very

   quickly

3) Validating data will become very easy

4) Processing data into python data structures like list, set etc will become easy

5) Creation of Models based on forms will become easy etc. 


Process to generate Django Forms:

Step-1: Creation of forms.py file in our application folder with our required fields.

forms.py:

               1) from django import forms

               2) class StudentForm(forms.Form):

               3)         name =  forms.CharField()

               4)         marks = forms.IntegerField()

Note: name and marks are the field names which will be available in html form

Step-2: usage of forms.py inside views.py file:

views.py file is responsible to send this form to the template html file


views.py:

             1) from django .shortcuts import render

             2) from .import forms

            3) #Create your views here.

           4) def studentinputview(request):

           5)         form=forms.StudentForm()

           6)          my_dict={‘form’:form}

           7)          return render(request,‘testapp/input.html’,

                                               context=my_dict)


Alternative Short Way: 

           1)def studentinputview(request):

           2        form=forms.StudentForm()

           3)          return render(request,‘testapp/input.html’,

                                               form=form)


Note: context parameter is optional.We can pass context parameter value directly

without using keyword name ‘context’

Step-3: Creation of html file to hold form:


            . Inside template file we have to use 

               template tag to inject form {{form}}


            It will add only form fields. But there 

              is no <form> tag and no submit button.

            Even the fields are not arranged properly.

              It is ugly form. 


We can make proper form as follows

             

           1) <h1>RegistrationForm</h1>

           2) <div class=“container” align=“center”>

           3) <form method=“post”>

          4) {{form.as_p}}

          5) <input type=“submit” class=“btn btn-primary” 

              name=“” value=“Submit”6) </form>

          7) </div>

input.html:

 

       1) <!DOCTYPEhtml>

       2) {%loadstaticfiles%}

       3) <htmllang=“en”dir=“ltr”>

       4) <head>

       5) <meta charset=“utf-8”>

       6) <link rel=“stylesheet” 

             href=”{%static “css/bootstrap.css”%}”>

       7) <link rel=“stylesheet” 

             href=”{%static “css/demo2.css”%}”>

       8) <title></title>

       9) </head>

      10) <body>

      11) <h1>Registration Form</h1>

      12) <div class=“container” align=“center”>

      13) <form method=“post”>

      14) {{form.as_p}}

     15) <input type=“submit” class=“btn btn-primary” 

            name=“” value=“Submit”>

     16) </form>
17) </div>

    18) </body>

    19) </html>

If we submit this form we will get 403 status code response

Forbidden (403)

CSRF verification failed. Request aborted.

Help

Reason given for failure:
                    CSRF token missing or incorrect.


CSRF (Cross Site Request Forgery) Token:

. Every form should satisfy CSRF (Cross Site Request 

  Forgery) Verification, otherwise Django won’t accept our form.

It is meant for website security. Being a programmer we 

 are not required to worry. anything about this. Django 

  will takes care everything.

But we have to add csrf_token in our form.


   1) <h1>RegistrationForm</h1>

   2) <div class=“container” align=“center”>

   3) <form method=“post”>

   4) {{form.as_p}}

   5) {% csrf_token %}

   6) <input type=“submit” class=“btn btn-primary” 

       name=“” value=“Submit”>

   7) </form>

   8) </div>

. If we add csrf_token then in the generate form the 

 following hidded field will be. added,which makes our post request secure

.  <input type=’hidden’ name=’csrfmiddlewaretoken’

    value=’1ZqIJJqTLMVa6RFAyPJh7pwzyFmdiHzytLxJIDzAkKULJz4qHcetLoKEsRLwyz4h’/>

.  The value of this hidden field is keep on changing from 

   request to request.Hence it is  impossible to forgery of our request.

.  If we configured csrf_token in html form then 

   only django will accept our form. 

How to process Input Data from the form inside views.py File:

We required to modify views.py file. 

The end user  provided input is available 

in a dictionary named with ‘cleaned_data’ 


views.py:

      1) from django .shortcuts import render

      2) from .import forms

      3)

      4) #Create your views here.

      5) def studentinputview(request):

      6)      form=forms.StudentForm()

      7)      if request.method==‘POST’:

      8)     form=forms.StudentForm(request.POST)

      9)     if form.is_valid():

     10)   print(‘Form validation success and printing data’)

     11)   print(‘Name:’,form.cleaned_data[‘name’])

    12)   print(‘Marks:’,form.cleaned_data[‘marks’])

    13)   return render(request,‘testapp/input.html’,

           {‘form’:form})

Student Name and Marks Submission Form Project (formproject1):


forms.py 

        1) from django import forms

        2) class StudentForm(forms.Form):

        3)          name=forms.CharField()

        4)          marks=forms.IntegerField()

views.py 

      1) from django .shortcuts import render

      2) from testapp .forms import StudentForm

      3) #Create your views here.

      4) def student_input_view(request):

     5)       sent=False

     6)       if request.method==‘POST’:

     7)           form=StudentForm(request.POST)

     8)          if form.is_valid():

     9)          print(‘Form Validation Success and printing data’)

    10)         print(‘Name:’,form.cleaned_data[‘name’])

    11)         print(‘Marks:’,form.cleaned_data[‘marks’])

    12)       sent=True

    13)     form=StudentForm()

    14)     return render(request,‘testapp/input.html’,{‘form’:form,‘sent’:sent})

input.html 

      1) <!DOCTYPEhtml>

      2) <htmllang=“en”dir=“ltr”>

      3) <head>

      4) <meta charset=“utf-8”>

     5) <title></title>

     6) <!– Latest compiled and minified CSS –>

     7) <linkrel=“stylesheet”href=“https://maxcdn.bootstrap

cdn.com/bootstrap/3.3.7/css/bootstrap.min.css” integrity=“sha384-

BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va

+PmSTsz/K68vbdEjh4u” crossorigin=“anonymous”>

        

     8) </head>

    9) <body>

   10) <div class=“container” align=‘center’>

   11) {% if sent %}

   12) <h1>Thanks for Providing Information</h1>

   13) <h2>Enter Next Student Marks</h2>

   14) {%else%}

   15) <h1>Student Marks Submit Form</h1>

   16) {%endif%}<hr>

 

   17) <form method=‘POST’>

   18) {{form.as_p}}

   19) {%csrf_token%}

   20) <input type=“submit” name=“” class=‘btn btn-lg 

         btn- primary’ value=“Submit Marks”>

   21) </form>

   22) </div>

   23) </body>

   24) </html>

thankyou.html 

   1) <!DOCTYPEhtml>

   2) <htmllang=“en”dir=“ltr”>

   3) <head>

   4) <meta charset=“utf-8”>

   5) <title></title>

   6) </head>

   7) <body>

   8) <h1>Thanks for providing your Name and Marks</h1>

  9) </body>

  10) </html>

urls.py 

  1) from django .conf .urls import url

  2) from django .contrib import admin

  3) from testapp import views

  4)

  5) urlpatterns=[

  6) url(r‘^admin/’, admin.site.urls),

  7) url(r‘^input/’, views.student_input_view),

  8) ]

Student FeedBack Form Project

forms.py: 

   1) from django import forms

   2)

  3) class FeedBackForm(forms.Form):

  4)           name=forms.CharField()

  5)           rollno=forms.IntegerField()

  6)          email=forms.EmailField()

  7)         feedback=forms.CharField

             (widget=forms.Textarea) 

views.py 

   1) from django .shortcuts import render

   2) from testapp .forms import StudentForm

   3) #Create your views here.

   4) def student_input_view(request):

   5)      sent=False

   6)       if request.method==‘POST’:

   7)          form=StudentForm(request.POST)

   8)          if form.is_valid():

   9)            print(‘Form Validation Success and printing data’)

  10)          print(‘Name:’,form.cleaned_data[‘name’])

  11)          print(‘Marks:’,form.cleaned_data[‘marks’])

  12)         sent=True

  13)     form=StudentForm()

  14)     return render(request,‘testapp/input.html’,

                                 {‘form’:form,‘sent’:sent})

input.html 

    1) <!DOCTYPEhtml>

    2) <htmllang=“en”dir=“ltr”>

   3) <head>

   4) <meta charset=“utf-8”>

   5) <title></title>

   6) <!– Latest compiled and minified CSS –>

   7) <linkrel=“stylesheet”href=“https://maxcdn.

        bootstrapcdn.com/bootstrap/3.3.7/cs

       s/bootstrap.min.css” integrity=“sha384-

      BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va

     +PmSTsz/K68vbdEjh4u” crossorigin=“anonymous”>

      

  8) </head>

  9) <body>

 10) <div class=“container” align=‘center’>

 11) {% if sent %}

 12) <h1>Thanks for Providing Information</h1>

 13) <h2>Enter Next Student Marks</h2>

 14) {%else%}

 15) <h1>Student Marks Submit Form</h1>

 16) {%endif%}<hr>

 17) <form method=‘POST’>

 18) {{form.as_p}}

 19) {%csrf_token%}

 20) <input type=“submit” name=“” class=‘btn btn-lg 

        btn-
primary’
value=“Submit Marks”>

 21) </form>

 22) </div>

 23) </body>

 24) </html>

thankyou.html 

 1) <!DOCTYPEhtml>

 2) <htmllang=“en”dir=“ltr”>

 3) <head>

 4) <meta charset=“utf-8”>

 5) <title></title>

 6) </head>

 7) <body>

 8) <h1>Thanks for providing your Name and Marks</h1>

 9) </body>

 10) </html>

urls.py

 1) from django .conf .urls import url

 2) from django .contrib import admin

 3) from testapp import views

 4)

 5) urlpatterns=[

 6) url(r‘^admin/’, admin.site.urls),

 7) url(r‘^input/’, views.student_input_view),

 8) ]

Student FeedBack Form Project

forms.py: 

  1) from django import forms

  2)

  3) class FeedBackForm(forms.Form):

  4)         name=forms.CharField()

  5)         rollno=forms.IntegerField()

  6)        email=forms.EmailField()

  7) feedback=forms.CharField(widget=forms.Textarea)


views.py

 1) from django .shortcuts import render

 2) from import forms

 3)

 4) def feedbackview(request):

 5)      form=forms.FeedBackForm()

 6)      if request.method==‘POST’:

 7)         form=forms.FeedBackForm(request.POST)

 8)         if form.is_valid():

 9)            print(‘Form Validation Success and printing information’)

 10)          print(‘Name:’,form.cleaned_data[‘name’])

 11)          print(‘Roll No:’,form.cleaned_data[‘rollno’])

 12)          print(‘Email:’,form.cleaned_data[’email’])

 13)          print(‘FeedBack:’,form.cleaned_data[‘feedback’])

 14)       return render(request,‘testapp/feedback.html’,{‘form’:form})

feedback.html

 1) <!DOCTYPEhtml>

 2) {%loadstaticfiles%}

 3) <htmllang=“en”dir=“ltr”>

 4) <head>

 5) <meta charset=“utf-8”>

 6) <link rel=“stylesheet” href=“https://maxcdn.

     bootstrapcdn.com/bootstrap/3.3.7

     /css/bootstrap.min.css” integrity=“sha384-

    BVYiiSIFeK1dGmJRAkycuHAHRg32

   OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u”

   crossorigin=“anonymous”>

 7) <link rel=“stylesheet” href=”{% static “css/demo4.css” %}”>

 8) <title></title>

 9) </head>

 10) <body>

 11) <div class=“container” align=‘center’>

 12) <h1>Student Feedback Form</h1><hr>

 13) <form class=“” action=“index.html” method=“post”>

 14) {{form.as_p}}

 15) {% csrf_token %}

16) <input type=“submit” class=“btn 

      btn-primary” value=“Submit Feedback”>

17) </form>

18) </div>

19) </body>

20) </html>

Form Validations:

Once we submit the form we have to perform validations like

1) Length of the field should not be empty

2) The max number of characters should be 10

3) The first character of the name should be ‘d’ etc

We can implement validation logic by using the following 2 ways.

1) Explicitly by the programmer by using clean methods

2) By using Django inbuilt validators

Note: All validations should be implemented in the forms.py file


Explicitly by the Programmer by using Clean Methods:

1) The syntax of clean method: clean_fieldname(self)

2) In the FormClass for any field if we define clean method then at the time of submit the

   form, Django will call this method automatically to perform validations. If the clean

   method won’t raise any error then only form will be submitted.

 1) from django import forms

 2)

 3) class FeedBackForm(forms.Form):

 4)         name=forms.CharField()

 5)        rollno=forms.IntegerField()

 6)        email=forms.EmailField()

 7)        feedback=forms.CharField(widget=forms.Textarea)

 8)

 9) def clean_name(self):

 10)     inputname=self.cleaned_data[‘name’]

 11)     if len(inputname) < 4:

 12)     raise forms.ValidationError(‘The Minimum no of characters in the name field

          should be 4′)

 13)    return inputname

forms.py

The returned value of clean method will be considered by Django at the time of

submitting the form.

1) from django import forms

2) from django .core import validators

3)

4) classFeedBackForm(forms.Form):

5)         name=forms.CharField()

6)         rollno=forms.IntegerField()

7)        email=forms.EmailField()

8)        feedback=forms.CharField(widget=forms.Textarea)

9)

10)       def clean_name(self):

11)             print(‘validating name’)

12)            inputname=self.cleaned_data[‘name’]

13)           if len(inputname) < 4:

14)              raise forms.ValidationError(‘The Minimum no of characters in the name field
should be 4’
)

15)               return inputname+‘pythonpower’

16)         def clean_rollno(self):

17)               inputrollno=self.cleaned_data[‘rollno’]

18)               print(‘Validating rollno field’)

19)               return inputrollno

20)          def clean_email(self):

21)                inputemail=self.cleaned_data[’email’]

22)                print(‘Validating email field’)

23)                return inputemail

24)          def clean_feedback(self):

25)                inputfeedback=self.cleaned_data[‘feedback’]

26)                print(‘Validating feedback field’)

27)               return inputfeedback

Server Console:

validating name

Validating rollno field

Validating email field

Validating feedback field

Form Validation Success and printing information

Name:pythonpower

Roll No: 101

Email: pythonpower@gmail.com

FeedBack: This is sample feedback 


Note:

1) Django will call these filed level clean methods automatically and we are not required

    to call explicitly.

2) Form validation by using clean methods is not recommended. 


Django’s Inbuilt Core Validators:

1) Django provides several inbuilt core validators to perform very common validations.

   We can use these validators directly and we are not required to implement.

2) Django’s inbuilt validators are available in the django.core module 

3) from django.core import validators

4) To validate Max number of characters in the feedback 

    as 40,we have to use inbuilt validators as follows. 


forms.py   

1) from django import forms

2) from django .core import validators

3)

4) class FeedBackForm(forms.Form):

5)         name=forms.CharField()

6)         rollno=forms.IntegerField()

7)         email=forms.EmailField()

8)         feedback=forms.CharField(widget=

                            forms.Textarea,validators= 

          [validators.MaxLengthValidator(40)])


                        

Note: We can use any number of validators for the same field

feedback = forms.CharField(widget = forms.Textarea,validators =

[validators.MaxLengthValidator(40),validators.MinLengthValidator(10)]) 

Note: Usage of built in validators is very easy when compared with clean methods.


How to implement Custom Validators by using the same

Validator Parameter:

The value of name parameter should starts with ‘d’ or ‘D’. We can implement this

validation as follows

1) def starts_with_d(value):

2)      if value[0].lower() != ‘d’:

3)      raise forms.ValidationError(‘Name should be starts with d | D’)

4)

5) class FeedBackForm(forms.Form):

6)         name=forms.CharField(validators=[starts_with_d])

7)         rollno=forms.IntegerField()

Validation of Total Form directly by using a Single Clean

Method:

Whenever we are submitting the form Django will call clean() method present in our Form

class. In that method we can implement all validations.

forms.py 

 1) from djangoi mport forms

 2) from django .core import validators

 3)

 4) class FeedBackForm(forms.Form):

 5)         name=forms.CharField()

 6)        rollno=forms.IntegerField()

 7)       email=forms.EmailField()

 8)       feedback=forms.CharField(widget=forms.Textarea)

 9)

 10) def clean(self):

 11)      print(‘Total Form Validation…’)

 12)      total_cleaned_data=super().clean()

 13)      inputname=total_cleaned_data[‘name’]

 14)     if inputname[0].lower() != ‘d’:

 15)        raise forms.ValidationError(‘Name parameter should starts with d’)

 16)        inputrollno=total_cleaned_data[‘rollno’]

 17)              if inputrollno <=0:

 18)                   raise forms.ValidationError(‘Rollno should be > 0’)

How to Check Original pwd and reentered pwd are same OR not in

Signup Form: 

forms.py 

 1) from django import forms

 2) from django .core import validators

 3)

 4) class FeedbackForm(forms.Form):

 5)          name=forms.CharField()

 6)          rollno=forms.IntegerField()

 7)          email=forms.EmailField()

 8)         feedback=forms.CharField(widget=forms.Textarea)

 9)

 10) def clean(self):

 11)       print(‘Total Form Validation by using 

            single clean method…’)

 12)       total_cleaned_data=super().clean()

 13)       inputname=total_cleaned_data[‘name’]

 14)              if inputname[0].lower() !=‘d’:

 15)                  raise forms.ValidationError(‘Name should 

                        starts with d|D’)

 16)                   inputrollno=total_cleaned_data[‘rollno’]

 17)                   if inputrollno<=0:

 18)                      raise forms.ValidationError(‘Rollno 

                            should be >0′)

 19) class SignupForm(forms.Form):

 20)          name=forms.CharField()

 21)           password=forms.CharField(widget=

                                  forms.PasswordInput)

 22)          rpassword=forms.CharField(label=‘Reenter 

                  Password’,widget=forms.PasswordIn
put)

 23)           email=forms.EmailField()

 24)

 25) def clean(self):

 26)       total_cleaned_data=super().clean()

 27)       pwd=total_cleaned_data[‘password’]

 28)       rpwd=total_cleaned_data[‘rpassword’]

 29)         if pwd != rpwd:

 30)             raise forms.ValidationError(‘Both Passwords 

                           must be same’)

views.py

 1) from django .shortcuts import render

 2) from testapp .forms import FeedbackForm,SignupForm

 3)

 4) #Createyourviewshere.

 5) def feedback_form_view(request):

 6)        form=FeedbackForm()

 7) # feedback_submitted=False

 8)        if request.method==‘POST’:

 9)           form=FeedbackForm(request.POST)

 10)         if form.is_valid():

 11)              print(‘Basic Validation Completed and Printing Data’)

 12)              print(‘Name:’,form.cleaned_data[‘name’])

 13)             print(‘RollNo:’,form.cleaned_data[‘rollno’])

 14)             print(‘Email:’,form.cleaned_data[’email’])

 15)             print(‘Feedback:’,form.cleaned_data[‘feedback’]) # feedback_submitted=True

 16)             return render(request,‘testapp/feedback.html’,{‘form’:form})

 17)

 18) def signup_form_view(request):

 19)       form=SignupForm()

 20)      if request.method==‘POST’:

 21)         form=SignupForm(request.POST)

 22)        if form.is_valid():

 23)           print(‘Basic Validation Completed and Printing Data’)

 24)           print(‘Name:’,form.cleaned_data[‘name’])

 25)           print(‘Password:’,form.cleaned_data[‘password’])

 26)           print(‘Email:’,form.cleaned_data[’email’])

 27)       return render(request,‘testapp/signup.html’,{‘form’:form})

signup.html

1) <!DOCTYPEhtml>

2) <htmllang=“en”dir=“ltr”>

3) <head>

4) <meta charset=“utf-8”>

5) <title></title>

6) <!– Latest compiled and minified CSS –>

7) <linkrel=“stylesheet”href=“https://maxcdn.

bootstrapcdn.com/bootstrap/3.3.7/cs
s/

bootstrap.min.css” integrity=“sha384-

BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3R

Ydg4Va+PmSTsz/K68vbdEjh4u” crossorigin=“anonymous”>

8) </head>

9) <body>

10) <div class=“container” align=‘center’>

11) <h1>Student Signup Form</h1><hr>

12) <form method=“post”>

13) {{form.as_p}}

14) {%csrf_token%}

15) <input type=“submit” class=‘btn btn-lg

      btn-warning’ value=“Signup”>

16) </form>

17) </div>

18) </body>

19) </html>

Note: If we want to perform validations by comparing multiple input fields then we

should go for single clean() method.


 

 

 

         

           

 


 

              

 

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *