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 neveropen having an app named Lazyroar.Â
Refer to the following articles to check how to create a project and an app in Django.Â
Â
In your Lazyroar 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,Â
Python3
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.Â
Python3
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Â
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