How to Create a form using Django Forms (original) (raw)
Last Updated : 26 May, 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 Form
Consider a project named **geeksforgeeks with an app called **geeks.
Refer to the following articles to check how to create a project and an app in Django.
Step 1: Create the Form Class
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 View
In 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 Template
Create or edit the home.html template inside your templates folder and add the following:
HTML `
{% csrf_token %} {{ form }}`
Now, visit http://localhost:8000/ to see your form rendered.
Improving Form Display
The default form rendering (****{{ form }}**) is functional but basic. Django provides convenient methods to change the form layout:
- ****{{ form.as_table }}:** renders the form fields wrapped in
table rows - ****{{ form.as_p }}:** renders form fields inside
tags
- ****{{ form.as_ul }}:** renders form fields inside
- list items
Customizing Individual Fields
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.