Django_Forms_notes (2)
Django_Forms_notes (2)
--------------
-->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.
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.
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'.
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.
If we add csrf_token then the generated form the following hidden field will be added,
which makes our post request secure.
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.
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
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()
-->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.
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)])
def gmail_validators(value):
print('Checking for gmail validations')
if value[-10:] != '@gmail.com':
raise forms.ValidationError('mail 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....')
-->Being a developer compulsory we have to think about BOT requests and we have
to prevent these requests.
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)
###############
5
###############
name = form.cleaned_data['name']
marks = form.cleaned_data['marks']
records = Student.get_or_create(name=name,marks=marks)
100 - fields
2).
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
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
models.py
---------
class Student(models.Model):
name = models.CharField(max_length=30)
marks = models.IntegerField()
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>