Last Updated : 12 Jul, 2025
This article explains how to create a basic form using various form fields and attributes. Creating a form in Django is very similar to creating a model, you define the fields you want and specify their types. For example, a registration form might need fields like First Name (CharField), Roll Number (IntegerField), and so on.
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.
Example: Creating a Django FormConsider a project named geeksforgeeks with an app called geeks.
Step 1: Create the Form ClassRefer to the following articles to check how to create a project and an app in Django.
Inside your app directory, create a file called forms.py where you will define all your forms. Use Django’s forms.Form class to create a form.
In forms.py, add the following code:
Python
from django import forms
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
Step 2: Render the Form in a ViewIn your app’s views.py, import the form and create a view to render it:
Python
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)
Here, an instance of the form is created and passed to the template context.
Step 3: Display the Form in a TemplateCreate or edit the home.html template inside your templates folder and add the following:
HTML
<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
Now, visit http://localhost:8000/ to see your form rendered.
Improving Form DisplayThe default form rendering ({{ form }}) is functional but basic. Django provides convenient methods to change the form layout:
You can render individual fields separately using:
{{ form.first_name }}
{{ form.last_name }}
Note: When rendering fields manually, make sure to handle validation and errors properly, and always include CSRF tokens in your form. Otherwise, you risk breaking Django’s built-in form validation.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4