Django Forms
Learn how to manage forms in Django - a comprehensive introduction for beginners
This page explains how to manage and validate a form in Django Framework. We assume the audience has already a Django project up and running. For those that start from nothing, feel free to access the resources mentioned below and come back here once the content is understood:
Topics covered by this tutorial
    Create a new Django app
    Define a new route
    Update the configuration to include the new application
    Code a simple form
    Visualize the form using Django shell
    Integrate the Form into a real page
    Update the controller to check the form is validated

Create a new Application

For this, we will use the startapp Django subcommand:
1
$ python manage.py startapp forms
Copied!
Add a simple view in forms - forms/views.py
1
# File contents: forms/views.py
2
​
3
from django.shortcuts import render
4
​
5
from django.http import HttpResponse
6
​
7
def index(request):
8
return HttpResponse("Hello Django - Forms")
Copied!
Define the routing for our new app - forms/urls.py
1
from django.urls import path, re_path
2
from forms import views
3
​
4
urlpatterns = [
5
​
6
# The home page
7
path('forms/', views.index, name='home'),
8
]
Copied!
Update settings to include the new app - config/settings.py
1
# File: config/settings.py (partial content)
2
...
3
INSTALLED_APPS = [
4
'django.contrib.admin',
5
'django.contrib.auth',
6
'django.contrib.contenttypes',
7
'django.contrib.sessions',
8
'django.contrib.messages',
9
'django.contrib.staticfiles',
10
'forms' # <-- NEW
11
]
12
...
Copied!
Update routing - config/urls.py
1
from django.contrib import admin
2
from django.urls import path, include # <-- UPDATED to add 'include'
3
​
4
urlpatterns = [
5
path('admin/', admin.site.urls),
6
path("" , include("forms.urls")), # Forms app routing
7
]
Copied!
Once we restart the project, the new route /forms should be visible:
Django Forms - A Hello-World type route

Define a new form

Inside the newly created app, we need to create a forms file and define the new Form Class object.
1
# File contents: forms/forms.py
2
​
3
from django import forms
4
5
class HelloForm(forms.Form):
6
​
7
title = forms.CharField()
8
message = forms.CharField()
9
email = forms.EmailField(required=False)
Copied!
After the file is saved, we can play with it using Django CLI.
1
$ python .\manage.py shell
2
>>>
3
>>> from forms.forms import HelloForm
4
>>>
5
>>> my_form = HelloForm()
6
>>>
7
>>> print( my_form.as_ul() )
8
<li><label for="id_title">Title:</label> <input type="text" name="title" required id="id_title"></li>
9
<li><label for="id_message">Message:</label> <input type="text" name="message" required id="id_message"></li>
10
<li><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></li>
Copied!
Using the CLI we can visualize how the form will be expended and presented to the users. Another helper provided by Django is form.as_p() - the paragraph view of a form.
1
>>>
2
>>> print( my_form.as_p() )
3
<p><label for="id_title">Title:</label> <input type="text" name="title" required id="id_title"></p>
4
<p><label for="id_message">Message:</label> <input type="text" name="message" required id="id_message"></p>
5
<p><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></p>
6
>>>
Copied!
The next step is to add the necessary code to display the form on a page and manage the information submitted by users in a controller.
Controller code - forms/forms.py - index method
1
from .forms import HelloForm
2
​
3
def index(request):
4
5
​
6
if request.method == 'POST':
7
form = HelloForm(request.POST)
8
if form.is_valid():
9
return HttpResponse("Form is valid")
10
11
else:
12
form = HelloForm()
13
​
14
return render(request, 'hello.html', {'form': form})
Copied!
HTML page - defined in forms/templates forlder
1
<!-- Forms/templates/hellp.html: partial content -->
2
​
3
<form action="" method="post">
4
<table>
5
{{ form.as_table }}
6
</table>
7
{% csrf_token %}
8
<br />
9
<input type="submit" value="Submit">
10
</form>
Copied!
Django Forms - Completed with user Data
If all fields are provided, on submit, we should see the Form is valid message.
Update the form with a new field ID (numeric type):
1
from django import forms
2
3
class HelloForm(forms.Form):
4
​
5
title = forms.CharField()
6
message = forms.CharField()
7
id = forms.IntegerField() # <-- NEW form field
8
email = forms.EmailField(required=False)
Copied!
The page server to the users is updated automaticaly to include the new field
Django Forms - Integer Field Added
​
Thanks for reading! For more topics, feel free to contact Appseed.
​

Resources

Last modified 3mo ago