0% found this document useful (0 votes)
12 views13 pages

Django_Forms_notes (2)

The document provides a comprehensive overview of Django Forms, detailing their importance in web development for user input handling and data validation. It explains the advantages of Django Forms over traditional HTML forms, the process of creating and using forms, and the implementation of CSRF protection. Additionally, it covers form validation techniques, including custom validators, and introduces Model Forms for easier database interactions.

Uploaded by

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

Django_Forms_notes (2)

The document provides a comprehensive overview of Django Forms, detailing their importance in web development for user input handling and data validation. It explains the advantages of Django Forms over traditional HTML forms, the process of creating and using forms, and the implementation of CSRF protection. Additionally, it covers form validation techniques, including custom validators, and introduces Model Forms for easier database interactions.

Uploaded by

desta melkamu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 13

Django Forms:

--------------
-->It is very important in web development.Django_Babu_formsp
-->The main purpose of forms is to take user input.

Ex:
login form, registration form, enquiry form etc....

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

Advantages of Django Forms over HTML Forms:


-------------------------------------------
-->We can develop forms very easily with python code.
-->We can generate HTML form widgets/components(like text area,emai;,pwd etc...)
very quickly.
-->Validating data will become very easy.
-->Processing data into python data structure like list, set etc will become very easy.
-->Creation of Models based on forms will become very easy.

model class---->Converted into database table.


form class-->Converted into HTML form.

Process to generate Django Forms:


----------------------------------
D:\Django_Babu_formsp>django-admin startproject formproject
D:\Django_Babu_formsp>cd formproject
D:\Django_Babu_formsp\formproject>py manage.py startapp testapp

-->Add app in settings.py

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

forms.py
--------
from django import forms
class StudentForm(forms.Form):
name = forms.CharField()
marks = forms.IntegerField()

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

forms.py=====>views.py=====>Template file (HTML)

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


----------------------------------------------
views.py file is responsible to send this form to the template file(html)
views.py
---------
from testapp.forms import StudentForm
def studentinput_view(request):
form = StudentForm()
my_dict = {'form':form}
return render(request,'testapp/input.html',context=my_dict)

Alternative way:
----------------
def studentinput_view(request):
form = StudentForm()
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 the form


---------------------------------------------
Inside template file we have to use template tag to inject form {{form}}

input.html
----------
<body>
<h1>Student Input Form</h1>
<div class="container">
<form method="post">
{{form.as_p}}
<input type="submit" class="btn btn-primary" name="" value="Submit">
</form>
</div>
</body>

form1.css
---------
h1{
text-align: center;
}
body{
background: yellow;
color: red;
}

urls.py
----------
from testapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('std/', views.studentinput_view),
]

-->If we sbmit the form we will get 403 status code response
Forbidden (403)
CSRF verification failed. Request aborted.

Help
Reason given for failure:
CSRF token missing.

CSRF(Cross Site Request Forgery) Token:


---------------------------------------
-->Every form should satisfy CSRF(Cross Site Request Forgery) verification,
otherwise django wont accept our form.
-->It is meant for website security. Being a programmer we are not required to worry
anything about this. Django will take care everything.
-->But we have to add csrf_token in our form.
<form method="post">
{{form.as_p}}
{% csrf_token %}
</form>

If we add csrf_token then the generated form the following hidden field will be added,
which makes our post request secure.

<input type="hidden" name="csrfmiddlewaretoken"


value="qf5hFyiVKDCaJxWfXK5CSDObKXYHnoDeelRgDdfISOCBIgv2Z0RM2G7qB
BnwopN3">

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
-------------------------------------------------------------

###############
2
###############

How to process input data from the form inside views.py file:
-------------------------------------------------------------
Inside views.py, We have to read data provided by end user and we have to use that
data based on our requirement.

form=StudentForm()-->empty form object to display form to the end user.


form=StudentForm(request.POST)-->This form object contains end user provided
data.

cleaned_data-->dictionary which contains end user provided data.


from.cleaned_data['name']-->The name entered by end user.
from.cleaned_data['marks']-->The marks entered by end user.

form.is_valid()--->To check whether validations are successful or not.

Difference between GET & POST:


-------------------------------
There are multiple ways to send GET request:
-->Typing URL in the address bar and enter
-->Clicking on hyperlinks
-->Submitting the HTML FORM without method attribute.
-->Submitting the HTML FORM with method attribute of GET value.
There is only one way to send POST request
-->Submitting the HTML FORM with method attribute POST value.

views.py
---------
from testapp.forms import StudentForm
# Create your views here.
def student_info(request):
submitted=False
sname=''
if request.method=='POST':
form=StudentForm(request.POST)
if form.is_valid():
print("Form validation success and print data")
print('Name:',form.cleaned_data['name'])
print('RollNo:',form.cleaned_data['rollno'])
print('Marks:',form.cleaned_data['marks'])
sname=form.cleaned_data['name']
submitted=True
form=StudentForm()
return render(request,'testapp/input.html',{'form':form,'submitted':submitted,
'sname':sname})

input.html
----------
<div class="container" align="center">
{% if submitted %}
<h1>Student with the name:{{sname}} processed successfully</h1>
<h2>Enter next student information</h2><hr>
{% else %}
<h1>Student Input Form</h1>
{% endif %}<hr>
<form method="post">
{{form.as_p}}
{%csrf_token%}
<input type="submit" name="" value="Submit Marks">
</form>

feedback project:
----------------
D:\Django_TVTI_Projects>django-admin startproject feedbackproject
D:\Django_TVTI_Projects>cd feedbackproject
D:\Django_TVTI_Projects>feedbackproject>py manage.py startapp testapp

forms.py
--------
from django import forms
class FeedBackForm(forms.Form):
name=forms.CharField()
rollno=forms.IntegerField()
email=forms.EmailField()
feedback=forms.CharField(widget=forms.Textarea)

views.py
--------
from testapp.forms import FeedBackForm
def feedback_view(request):
submitted=False
name=''
if request.method=='POST':
form=FeedBackForm(request.POST)
if form.is_valid():
print("Form validation success and printing feedback information")
print("*"*55)
print("Name:",form.cleaned_data['name'])
print("Rollno:",form.cleaned_data['rollno'])
print("MailID:",form.cleaned_data['email'])
print("Feedback:",form.cleaned_data['feedback'])
submitted=True
name=form.cleaned_data['name']
form=FeedBackForm()
return render(request,'testapp/feedback.html',{'form':form,'submitted':submitted,
'name':name})

feedback.html
-------------
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href={%static 'css/feed.css' %}>
</head>
<body>
<div class="container" align='center'>
{%if submitted %}
<h1>Hello {{name}}, thanks for providing feedback,
it is very helpful for us to provide better service</h1>
{% else %}
<h1>Student Feedback Form</h1>
<form method="post">
{{form.as_p}}
{% csrf_token %}
<input type="submit" name="" value="SubmitFeedback">
</form>
{% endif %}
</div>
</body>
</html>

feed.css
---------
body{
background:yellow;
color:red;

background:url();
background-repeat:no-repeat;
background-size:cover;
}

urls.py
-------
path('feed/','views.feedback_view')

###############
3
###############

Form Validations:
-----------------
1.clean methods
2.django inbuilt validators

Basic OOP knowledge:


-------------------
class Parent:
def __init__(self):
self.x = 333
def property(self):
print('gold + land + cash')
class Child(Parent):
def education(self):
print('B.Tech qualification + Job')
c = Child()
c.education()
c.property()
print(c.x)

Ex:
class Form:
def __init__(self):
self.cleaned_data = {'name':'Babu'}
class FeedBackForm(forms.Form):
name = forms.CharField()
rollno = forms.IntegerField()
email = forms.EmailField()
feedback = forms.CharField(widget=forms.Textarea)

form = FeedBackForm()
form.cleaned_data['name']

Overriding:
----------
class Parent:
def marry(self):
print('Appalamma')
class Child(Parent):
def marry(self):
super().marry()
print('Marry Katrina Kaif')
c = Child()
c.marry()

1).Explicitly by the programmer by using clean methods:


-------------------------------------------------------
Syn:
clean_fieldname(self)

-->In the Form class, for any field, if we define clea method, then at the time of
submit this form, django will call this method automatically to perform validations. If
clean method wont raise any error then only request will be processed.

forms.py
--------
def clean_name(self):
print('Validating name field')
inputname = self.cleaned_data['name']
if len(inputname) < 4:
raise forms.ValidationError('The minimum number of characters in the
name field should be 4')
return inputname
def clean_rollno(self):
print('Validating rollno field')
inputrollno = self.cleaned_data['rollno']
return inputrollno
def clean_email(self):
print('Validating email field')
inputemail = self.cleaned_data['email']
return inputemail
def clean_feedback(self):
print('Validating feedback field')
inputfeedback = self.cleaned_data['feedback']
return inputfeedback

Note:
Django will call these field level clean methods automatically and we are not
required to call these methods explicitly. The names are fixed because these are
understandable by Django.

2).By using django inbuilt validators:


--------------------------------------
-->Django provides several inbuilt validators to perform very common validations. We
can use directly and we are not responsible to implement those.
All inbuilt validators present in django.core module

forms.py
---------
from django.core import validators
class FeedBackForm(forms.Form):
name = forms.CharField()
rollno = forms.IntegerField()
email = forms.EmailField()
feedback =
forms.CharField(widget=forms.Textarea,validators=[validators.MaxLengthValidator(4
0),validators.MinLengthValidator(10)])

How to implement custom validators by using same validators parameter?


----------------------------------------------------------------------
Ex:The name should be starts with 's'
class FeedBackForm(forms.Form):
def starts_with_s(value):
print('starts-with_s function execution....')
if value[0].lower() != 's':
raise forms.ValidationError('Name should be starts with s or S')
name = forms.CharField(validators=[starts_with_s])
rollno = forms.IntegerField()
email = forms.EmailField()
feedback =
forms.CharField(widget=forms.Textarea,validators=[validators.MaxLengthValidator(4
0),validators.MinLengthValidator(10)])

mail should contain @gmail.com


--------------------------------
mail = 'Babu@gmail.com'
print(mail[-10:])

def gmail_validators(value):
print('Checking for gmail validations')
if value[-10:] != '@gmail.com':
raise forms.ValidationError('mail extension should be gmail')

Validation of total form directly by using single clean() method:


------------------------------------------------------------------
###############
4
###############

Validation of total form directly by using single clean() method:


------------------------------------------------------------------
def clean(self):
print('Total Form Validation......')
total_cleaned_data = super().clean()
print('Validating Name')
inputname = total_cleaned_data['name']
if inputname[0].lower() != 's':
raise forms.ValidationError('Name should be starts with s')
print('Validating Rollno')
inputrollno = total_cleaned_data['rollno']
if inputrollno <= 0:
raise forms.ValidationError('Rollno should be > 0')
print('Validating email')
inputmail = total_cleaned_data['email']
if inputmail[-10:] != '@gmail.com':
raise forms.ValidationError('Email extension should be gmail')

How to check original pwd and re-entered pwd are same or not?
--------------------------------------------------------------
class FeedBackForm(forms.Form):
name = forms.CharField()
rollno = forms.IntegerField()
email = forms.EmailField()
password = forms.CharField(label='Enter
Password',widget=forms.PasswordInput)
rpassword =
forms.CharField(label='Password(Again)',widget=forms.PasswordInput)
feedback = forms.CharField(widget=forms.Textarea)

def clean(self):
total_cleaned_data = super().clean()
pwd = total_cleaned_data['password']
rpwd = total_cleaned_data['rpassword']
if pwd != rpwd:
raise forms.ValidationError('Both passwords must be same....')

How to prevent request from BOT:


--------------------------------
-->Generally form requests can be send by end user. Sometimes we can write
automated programming script which is responsible to fill the form and submit. This
automated programming script is nothing but BOT.

The main objective of BOT requests are:


1).To create unneccessary heavy traffic to the website, which may crash our
application.
2).To spread malware(viruses)

-->Being a developer compulsory we have to think about BOT requests and we have
to prevent these requests.

How to prevent BOT request:


--------------------------
-->In the form we will place one hidden field, which is not visible to the end user,
Hence there is no chance of providing value to this hidden field.
-->But BOT will send the value for this hidden field also. If hidden field got some
value means it i sthe request from BOT and prevent that submission.

class FeedBackForm(forms.Form):
All fields
bot_handler = forms.CharField(required=False,widget=forms.HiddenInput)

def clean(self):
total_cleaned_data = super().clean()
bot_handler_value = total_cleaned_data['bot_handler']
if len(bot_handler_value) > 0:
raise forms.ValidationError('Request from BOT....cant submit....')

Note:
Otherway to prevent BOT requests
1).By using captcha
2).By using image recognizers
(like choose 4-images where car present)

Working with Model Forms:


========================

###############
5
###############

Working with Model Forms:


========================
Model Form====>Model based form
Read each field value

name = form.cleaned_data['name']
marks = form.cleaned_data['marks']
records = Student.get_or_create(name=name,marks=marks)

100 - fields

model based form


only one line
form.save()

How to develop model based form:


---------------------------------
class Student(forms.Form)--->Normal Form
class Student(forms.ModelForm)-->Model Form

2).
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'

3).Instead of all fields, if we required particular fields.


class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ('field1','field2','field3')

4).Instead of all fields, if we want to exclude certain fields.


class StudentForm(forms.ModelForm):
class Meta:
model = Student
exclude = ['field1','field2']

How to save users data to database in model based form:


--------------------------------------------------------
views.py
--------
def student_view(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()

Ex:ModelFormProject
------------------
D:\Django_Babu_formsp>django-admin startproject modelformproject
D:\Django_Babu_formsp>cd modelformproject
D:\Django_Babu_formsp\modelformproject>py manage.py startapp testapp

-->add app in settings.py

models.py
---------
class Student(models.Model):
name = models.CharField(max_length=30)
marks = models.IntegerField()

-->makemigrations and migrate.

admin.py
--------
from testapp.models import Student
class StudentAdmin(admin.ModelAdmin):
list_display = ['name','marks']
admin.site.register(Student,StudentAdmin)

forms.py
--------
from django import forms
from testapp.models import Student
class StudentForm(forms.ModelForm):
name = forms.CharField()
marks = forms.IntegerField()
class Meta:
model = Student
fields = '__all__'

views.py
------------
from testapp.forms import StudentForm
def student_view(request):
form = StudentForm()
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save(commit=True)
print('Record inserted into database successfully.....')
return render(request,'testapp/studentform.html',{'form':form})

studentform.html
-----------------
<body>
<div class="container" align='center'>
<h1>Student Registration Form</h1>
<form method="post">
{{form.as_p}}
{% csrf_token %}
<input type="submit" class="btn btn-primary" name="" value="Register">
</form>
</div>
</body>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy