Django forms are an advanced set of HTML forms that can be created using python and support all features of HTML forms in a pythonic way. This post revolves around how to create a basic form using various Form Fields and attributes. Creating a form in Django is completely similar to creating a model, one needs to specify what fields would exist in the form and of what type. For example, to input, a registration form one might need First Name (CharField), Roll Number (IntegerField), and so on.
Creating a form using Django Forms
Illustration of Django Forms using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
In your geeks app make a new file called forms.py where you would be making all your forms. To create a Django form you need to use Django Form Class. Let’s demonstrate it.
In your forms.py Enter the following,
from django import forms
# creating a form class InputForm(forms.Form):
first_name = forms.CharField(max_length = 200 )
last_name = forms.CharField(max_length = 200 )
roll_number = forms.IntegerField(
help_text = "Enter 6 digit roll number"
)
password = forms.CharField(widget = forms.PasswordInput())
|
Let’s explain what exactly is happening, left side denotes the name of the field and to the right of it, you define various functionalities of an input field correspondingly. A field’s syntax is denoted as
Syntax :
Field_name = forms.FieldType(attributes)
Now to render this form into a view, move to views.py and create a home_view as below.
from django.shortcuts import render
from .forms import InputForm
# Create your views here. def home_view(request):
context = {}
context[ 'form' ] = InputForm()
return render(request, "home.html" , context)
|
In view, one needs to just create an instance of the form class created above in forms.py. Now let’s edit templates > home.html
< form action = "" method = "post" >
{% csrf_token %}
{{form }}
< input type = "submit" value = Submit ">
</ form >
|
All set to check if the form is working or not let’s visit http://localhost:8000/
The form is working properly but visuals are disappointing, Django provides some predefined ways to show forms in a convenient manner. In templates, the following will modify the inputs as,
- {{ 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
One can modify these settings also and show fields as he wants using {{ form.field_name }} but this may alter the normal process of validation if some field is empty and hence needs extraordinary care. More – Django Forms