D jan g o Fram ew ork
D JANGO FORM S
Django Form
● Django’s form functionality can simplify and automate vast portions of work
like data prepared for display in a form, rendered as HTML, edit using a
convenient interface, returned to the server, validated and cleaned up etc.
● It can also do it more securely than most programmers would be able to do in
code they wrote themselves.
By - Rahul Gupta
Django Form
Django handles three distinct parts of the work involved in forms:
● Preparing and restructuring data to make it ready for rendering
● Creating HTML forms for the data
● Receiving and processing submitted forms and data from the client
By - Rahul Gupta
Types of Forms
● Bound Forms:
● If it’s bound to a set of data, it’s capable of validating that data and rendering
the form as HTML with the data displayed in the HTML.
● Unbound Forms:
● If it’s unbound, it cannot do validation (because there’s no data to validate!),
but it can still render the blank form as HTML.
By - Rahul Gupta
Create Django Form using Form Class
● To create Django form we have to create a new file inside application folder
lets say file name is forms.py.
● Syntax:
from django import forms
class FormClassName(forms.Form):
label=forms.FieldType()
label=forms.FieldType(label=‘display_label’)
By - Rahul Gupta
Display Form to User
● Create an object of Form class in views.py then pass object to template files
● Use Form object in template file
from .forms import StudentRegistration
def showformdata(request):
fm = StudentRegistration()
return render(request, ‘enroll/userregistration.html’, {‘form’:fm})
By - Rahul Gupta
Get object from views.py in template file
{{form}} doesn’t add form tag and button so we have to add them manually.
templates/enroll / userregistration.html
<!DOCTYPE html>
<html>
<body>
<form action =“” method=“get”>
{{form}}
<input type=“submit” value=“Submit”>
</form>
</body>
</html>
By - Rahul Gupta
Form Rendering Options
● {{form}} will render them all
● {{ form.as_table }} will render them as table cells wrapped in <tr> tags
● {{ form.as_p }} will render them wrapped in <p> tags
● {{ form.as_ul }} will render them wrapped in <li> tags
● {{ form.name_of_field }} will render field manually as given
By - Rahul Gupta