Introduction to Django Forms
For a web application creation forms is a critical capability, These forms act as the key source through which the user keyed in input enters into the application. This user keyed-in input could be further validated and processed in a precise manner. These are among the key capabilities in form processing. Django offers a classified set of methods for formulating the form entities.
How to Create a Django Form?
Create a Django form are explain below:
1. Create a forms.py file in the application
The forms.py file is similar to models.py, All fields used in the form will be declared here under a form class.
Example – forms.py
from django import forms
class Valueform(forms.Form):
user = forms.CharField(max_length = 100)
2. Create a View for The Form
A Django view method is created for the form in the views.py file. An object for the form class is created here. this object is used as a value for the context dictionary in the template rendering.
Example – views.py
from django.shortcuts import render
from django.http import HttpResponse
from Django_app1.forms import Valueform
defform_view(request_iter):
form = Valueform()
return render(request_iter,'Form_Handeling.html', {"form": form})
3. Formulate an HTML file for displaying the form
An HTML file needs to be created in the templates directory for displaying the form, here the file is template tagged using the below tag,
{{ form.as_p}}
here “as_p” is used for better designing of the form elements. the {% csrf_token %} line is used for attesting the internal security verification performed by django.
Example
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Django App1</title>
</head>
<body>
<h1><u> FORMS HANDELING IN DJANGO </u></h1
<div style = "max-width:470px;">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" class="btnbtn-primary" value="submit">
</div>
</body>
</html>
4. Tag the view in urls.py file
This is the process of creating a url for the view.
- Import the library from django.conf.urls import url
- declare a url entry in the urlpatterns list
url(url_path,view_to_be_tagged,name_for_this_view)
Example
from django.contrib import admin
from django.conf.urls import url
from Django_app1 import views
urlpatterns = [
url(r'^$',views.index,name='index'),
url(r'formpage/',views.form_view,name='form'),
url(r'admin/', admin.site.urls), ]
Output:
All Form Fields Available in Django Forms
Form fields available in django forms are as given below:
Field type | Django form field type | HTML output | Description | Django Widget |
Boolean | forms.BooleanField() | <input type=’checkbox’> | Creates a Boolean field | forms.widgets.CheckboxInput() |
Boolean | forms.NullBooleanField() | <select> <option value=”1″ selected=”selected”> Unknown </option> <option value=”2″> Yes </option> <option value=”3″> No </option> </select> |
Very similar to Boolean fields but also allows unknown value | forms.widgets.NullBooleanSelect() |
Text | forms.CharField() | <input type=”text”> | Creates a simple character field | forms.widgets.TextInput() |
Text | forms.EmailField() | <input type=”email”> | Creates a field for email Input | forms.widgets.EmailInput() |
Text | forms.GenericIPAddressField() | <input type=”text”> | Allows insertion of ip address | forms.widgets.TextInput() |
Text | forms.RegexField( regex=’regular_expression’) | <input type=”text”> | A basic character field but here validation happens on the server side | forms.widgets.TextInput() |
Text | forms.SlugField() | <input type=”text”> | A basic character field but allows only lowercase values to be entered | forms.widgets.TextInput() |
Text | forms.URLField() | <input type=”url”> | Allows insertion of url | forms.widgets.URLInput() |
Text | forms.UUIDField() | <input type=”text”> | A basic character field but server side the django validates whether the values is convertible to a UUID(Universal unique ID) | forms.widgets.TextInput() |
Text | forms.ComboField(fields=[field_type#1,field_type#2]) | <input type=”text”> | Works just like CharField, Heredjango form fields are enforced with data pass rules on the server side. | forms.widgets.TextInput() |
Text | forms.MultiValueField(fields=[field_type#1, field_type#1]) | <input type=”text”> | Allows creating form fields in custom manner. | forms.widgets.TextInput() |
Text / Files | forms.FilePathField( path=’directory’) | <select> <option value=”directory/file_1″> file_1 </option> <option value=”directory/file_2″> file_2 </option> <option value=”directory/file_3″> file_3 </option> </select> |
This field is used for holding path of the directory | forms.widgets.Select() |
Files | forms.FileField() | <input type=”file”> | Creates a field through which the user can attach a file to the form | forms.widgets.ClearableFileInput() |
Files | forms.ImageField() | <input type=”file”> | Creates a field through which the user can attach an image to the form | forms.widgets.ClearableFileInput() |
Date/time | forms.DateField() | <input type=”text”> | Works like a basic character field but on the server end the django setup validates whether the inserted value is of Date format. (e.g. 2020-11-23, 11/23/20). | forms.widgets.DateInput() |
Date/time | forms.TimeField() | <input type=”text”> | Works like a basic character field but on the server end the django setup validates whether the inserted value is of time format. (e.g. 15:41:32, 11:44). | forms.widgets.TextInput() |
Date/time | forms.DateTimeField() | <input type=”text”> | Works like a basic character field but on the server end the django setup validates whether the inserted value is of datetime format. (e.g. 2020-11-15 12:30:59, 11/15/20 13:30). | forms.widgets.DateTimeInput() |
Date/time | forms.DurationField() | <input type=”text”> | Works like a basic character field but on the server end the django setup validates whether the inserted value to be converted to time delta. | forms.widgets.TextInput() |
Number | forms.IntegerField() | <input type=”number” | In the server end django verifies whether the input field is a valid integer. | forms.widgets.NumberInput() |
Number | forms.DecimalField() | <input type=”number” | In the server end django verifies whether the input field is a valid decimal. | forms.widgets.NumberInput() |
Number | forms.FloatField() | <input type=”number” | In the server end django verifies whether the input field is of float type. | forms.widgets.NumberInput() |
Example – forms.py
The forms.py file below contains several among the above-mentioned form fields declared and executed as an application.
#-*- coding: utf-8 -*-
from django import forms
class Valueform(forms.Form):
first_name = forms.CharField(max_length = 100)
last_name = forms.SlugField()
gender = forms.BooleanField()
Ip = forms.GenericIPAddressField()
file = forms.FileField()
department = forms.ChoiceField(choices = (('1','CSE'),('2','IT'),('3','ECE'),('4','EEE')))
Output:
Processing Form Fields in View
The value entered in the form fields can be captured and processed using the below form handling code in the view method for the form
Example – views.py
from django.shortcuts import render
from django.http import HttpResponse
from Django_app1.forms import Valueform
defform_view(request_iter):
form = Valueform()
if request_iter.method == "POST":
value = Valueform(request_iter.POST)
if value.is_valid():
print("First Name: ",value.cleaned_data['first_name'])
print("First Name: ",value.cleaned_data['last_name'])
return render(request_iter,'Form_Handeling.html', {"form": form})
Here when a ‘POST’ is submitted from the form it is passed as a part of the request thread in the method argument, so this is verified in the below statement,
if request_iter.method == "POST":
So when a ‘POST’ is submitted then the value associated with the POST request is captured into an object by referring to the form class declared in forms.py. using the cleaned_data[] argument of this object and using the name of the corresponding field the value keyed from the field is captured. In this example, the captured value is printed onto the console. In real-time cases, further processing will be done to these values like DB storage or server validation, etc.
Output: