In this Python Django tutorial, I will explain working with Django forms.
As a Python Django developer, while working on a Django project I got a requirement of gathering information from the users. So, I have done the research and discovered that we can create web form in Python Django.
Here we will see:
- What is a web form
- Types of forms in Django
- How Django forms work
- Various form fields in Django
- How to create web form in Python Django using the Form class
- How to create web form in Python Django using ModelForm class
- How to use various controls like textbox, drop-down, email, datepicker, and radio buttons in Django
- How to upload files in Django form
At the end of this article, you can also download the code for both Django Forms using the Form class and ModelForm class.
Working with Django forms
Now, let us first understand the Django forms and learn step by step to create Django forms using the Form class and ModelForm class.
Web Form
A web form is a web page with many fields for the user to enter data or information.
Different fields, including text boxes, checkboxes, radio buttons, number boxes, image boxes, date pickers, and others, are used in forms to collect various types of data.
Additionally, each field has a field label so that anyone viewing the form may understand what each field contains.
And the ability to submit data through POST requests makes forms another pretty secure way to share data with the server.
Read: Python Django vs Pyramid
Types of form in Django
The next step is to understand the various form types that Django offers after knowing web forms. So, there are two types of forms in Django as follows.
- Simple Django forms: Simple forms are forms that are independent of the model. To create the form forms.Form class is used. It basically creates HTML forms and describes how it works and appears.
- Django forms with model: Forms with the model are similar to simple forms, but it requires the model. To create the model form forms.ModelForm class is used.
Read: Python Django set timezone
How Django forms work
Generally, simple HTML is used to present these forms, and JavaScript and CSS can be used to style them.
Fortunately, the Django framework offers forms, that simplify the process and save the developer to start from zero when constructing a form.
According to the diagram above, Django’s form works in the following way:
- When a user requests a form for the first time, the default form is shown.
- The validity of the data is then verified.
- If so, it executes the necessary actions, including saving the data and providing the outcome.
- If not, the form is once more displayed with user-entered data and error notices.
- Finally, it directs to another page after the form is successfully submitted.
Read: Python Django vs ReactJS
Various fields in the Django form
As discussed above web form is a web page with many fields, so we can say that the fields are the most important part of the form.
So, to have a look at the list of all the Form Field types used in Django.
from django import forms
dir(forms)
The following are the most frequently used fields of Django form.
Field Name | Class | HTML Input |
CharField | class CharField(**kwargs) | TextInput |
EmailField | class EmailFoeld(**kwargs) | EmailInput |
PasswordField | class PasswordField(**kwargs) | PasswordInput |
IntegerField | class IntegerField(**kwargs) | NumberInput |
DecimalField | class DecimalField(**kwargs) | NumberInput |
DateField | class DateField(**kwargs) | DateInput |
DateTimeField | class DataTimeField(**kwargs) | DateTimeInput |
BooleanField | class BooleanField(**kwargs) | CheckboxInput |
ChoiceField | class ChoiceField(**kwargs) | Select |
FileField | class FileField(**kwargs) | ClearableFileInput |
ImageField | class ImageField(**kwargs) | ClearableFileInput |
Read: How to Create model in Django
How to create web form in Python Django using the Form class
Set up Django Project
Firstly, we need to establish a project in Django using the below-given command. Here SurveyProject is the name of the project.
django-admin startproject SurveyProject
Now, within the Django project, create a Django app named SurveyApp using the command as follows.
python manage.py startapp SurveyApp
Open the settings.py file located in the project directory, and add SurveyApp to the INSTALLED_APP list.
A request in Django first comes to urls.py located inside the project directory and then goes to the matching URLs in urls.py inside the app directory. Add the below code in it.
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('SurveyApp.urls')),
]
Read: Python Django MySQL CRUD
Create Django Form using Form Class
Create the Django form that the SurveyApp application will use to collect user input. Add the following code to the forms.py file you create inside the app directory.
from django import forms
# Create your forms here.
CITY_CHOICES =(
("1", "New York"),
("2", "Washington"),
("3", "Los Angeles"),
("4", "Houston"),
("5", "Las Vegas"),
)
class CustomerForm(forms.Form):
name = forms.CharField(max_length=50)
address = forms.CharField(max_length=150)
city = forms.ChoiceField(choices=CITY_CHOICES)
pincode = forms.IntegerField()
email = forms.EmailField()
phone = forms.IntegerField()
Here, we create a form using forms.Form class named CustomerForm. And following are the fields that the form consists of.
- The name and address as Django CharFields. And there is a 50-character limit for name and a 150-character limit for address.
- The pincode and phone as Django IntegerFields.
- The email is Django EmailField which allows users to save email address.
- The city is Django ChoiceField and there is a choices option that may be used as options for a field and consists of iterables for items.
- And we define a tuple for this named CITY_CHOICES.
Read: Django contact form with class-based views
Render the form as a table in Django
Create a subdirectory called Templates in the main project directory to store the front end of a Django application.
Open the settings.py file, and update the DIRS to refer to the Templates folder’s location.
To define the front end of the survey webpage create an HTML file named forms.html inside the Templates folder. And add the below-given code.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width={device-width}, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="POST" class="post-form"> {% csrf_token %} <h1 align="center">Coustomre Survey</h1> <table> {{ form.as_table}} </table> <button type="submit" class="save btn btn-default">Submit</button> </form> </body> </html>
- Firstly add the heading to the form using the HTML tag h1. Then call the form tag with the method POST, so the form is posted upon submission.
- To prevent the form from cyber attacks and allow you to send the information securely, add the {% csrf_token %} within the form element.
- Next, call the form and present it as a table by using the {{form.as_tabel}} tag. Pass this tag within the table tag as we render the form in the table.
- Lastly, add a submit button to submit the form.
Read: Build a Django Contact Form with Email
Define View
To define the main logic for the form open the views.py file and add the code given below.
from django.shortcuts import render from .forms import CustomerForm # Create your views here. def customer(request): if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): Name = form.cleaned_data['name'] Address = form.cleaned_data['address'] City = form.cleaned_data['city'] Pincode = form.cleaned_data['pincode'] Email = form.cleaned_data['email'] Phone = form.cleaned_data['phone'] print('Name:', Name) print('Full Address:', Address, City, Pincode) print('Email:', Email) print('Phone:', Phone) form = CustomerForm() return render(request, "forms.html", {'form':form})
- First, import the CoustomerForm from the forms.py and create a view named customer.
- Then call the if statement and check whether the request method is POST.
- If yes, we pass CoustomerForm(request.POST) that binds the data to the form class, so we can do validation.
- Now, call the is_valid method to validate the input entered by the user, and if validation success call the form cleaned_data[‘form field’] to validate the data.
- And use the print() function to display the user result on the terminal.
- If the request method is GET, the user is presented with a blank survey form using the render() function.
Now, we must map the view with the URL in order to call it, thus we must create a file called urls.py in the app directory. Include the code below in it.
from django.urls import path from SurveyApp import views urlpatterns = [ path("", views.customer, name="customer"), ]
Execute Django Application
To launch a development server type the below-given command in the terminal and run the server.
python manage.py runserver
It successfully opens the Customer Survey Form which looks like this.
Now, fill out this contact form and click on the Submit button as follows.
After clicking on submit, it will print the Name, Full Address, Email, and Phone on the terminal.
This is how you create a Django form using the Form class.
Read: Python Django group by
How to create web form in Python Django using the ModelForm class
Setup Django Project
Django web application always has one project with multiple apps inside of it. So, we need to create a project first by using the below-given command.
django-admin startproject CareerClub
Now, it’s time to create an app inside the Django project. So, type the below-given command in the terminal.
python manage.py startapp Apply
To consider the app in our project we need to include our project name in the INSTALLED_APPS list as follows in the settings.py file located inside the project directory.
Django automatically creates a urls.py file in the project directory. And to route our app, we need to include Apply app inside it as shown below.
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('Apply.urls')),
]
Create Django Model
We received an empty SQLite database when we created the Django project. And to create a new table inside it, we must create a new model.
To create models in Django open the models.py file inside the app directory and add the below-given code.
from django.db import models
# Create your models here.
class Resume(models.Model):
full_name = models.CharField(max_length=150)
gender = models.CharField(max_length=10)
date_of_birth = models.DateField()
email = models.EmailField()
current_address = models.CharField(max_length=300)
city = models.CharField(max_length=20)
state = models.CharField(max_length=20)
resume = models.FileField(upload_to='resumes/')
def __str__(self):
return self.full_name
Here, we create a model class Resume which has the following fields.
- The full_name is Django CharFields. And there is a 150-character limit for this character field.
- The gender is Django CharFields. And there is a 10-character limit for this character field.
- The date_of_birth is Django DateFields. And it is used to collect the date of birth from the user.
- The email is Django EmailField which allows users to save email addresses.
- The cuurent_address is Django CharField. And there is a 300-character limit for this character field.
- The city and state are Django CharFields. And these fields have a max_length limit of 20.
- The resume is Django FileField used to upload the files. Additionally, it has a upload_to option that defines the location within the media where the file will be saved.
And to change the display name of the object in the Django model use the def __str__(self). It will render the item name as the full name as we return the self.full_name.
Register the model to the admin site so that the user can view it in the admin application. Open the admin.py file and add the below-given code.
from django.contrib import admin
from .models import Resume
# Register your models here.
admin.site.register(Resume)
Read: Union operation on models Django
Create Web Form in Python Django using ModelForms Class
If we’re building a database-driven app with Django forms and Django models. In that situation, the quality and amount of model fields and form fields would be the same for both the model and the form.
Rather than writing duplicate code to first generate a form and then map it to the model in a view, we can directly use ModelForm.
To create a form add the following code to the forms.py file we created inside the app directory.
from django import forms
from .models import Resume
select_gender = (
("male", "Male"),
("female", "Female"),
("other", "Other"),
)
class DateInput(forms.DateInput):
input_type = 'date'
select_city = (
("new york", "New York"),
("los angeles", "Los Angeles"),
("houston", "Houston"),
("chicago", "Chicago"),
("phoenix", "Phoenix"),
("austin", "Austin"),
("boston", "Boston"),
("las vegas", "Las Vegas"),
("columbia", "Columbia"),
("waco", "Waco"),
)
select_state = (
("new york", "New York"),
("california", "California"),
("iiiinois", "IIIinois"),
("texas", "Texas"),
("arizona", "Arizona"),
("massachusetts", "Massachusetts"),
("nevada", "Nevada"),
("south carolina", "South Carolina"),
)
class ResumeForm(forms.ModelForm):
class Meta:
model = Resume
fields = '__all__'
widgets = {
"gender": forms.RadioSelect(choices=select_gender),
"date_of_birth": DateInput,
"city": forms.Select(choices=select_city),
"state": forms.Select(choices=select_state),
}
- Here, we create a form using forms.ModelForm class named ResumeForm. It has all the fields from the Resume model.
- Additionally, we define the widgets attribute that sets gender as a radio button, date_of_birth as DatePicker, city, and state as a drop-down button.
- The city and state are set as Select, a choices option is passed that are sequences used as options for a field. We define tuple select_city for the city field and select_state for the state field.
- The gender is set as RadioSelect, a choices option is passed that are sequences used as options for a field. We define tuple select_gender for the gender field.
Setup for Django file upload
As we have used the FileField in the model to upload files. We have to set some settings to save the uploaded files.
For this, open the settings.py file and add the below-given lines at the end of the file.
import os
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
- MEDIA URL: The user can upload files from their browser using this URL.
- MEDIA ROOT: This specifies the primary location of the file’s storage. It instructs Django to save all uploaded files in a folder called media.
Note: To save the submitted files, we must manually create the folder named media inside the main project directory.
Read: Django for loop
Render the form as a table in Django
In Django, the front end of the application is defined in Templates, so for this, create a subdirectory called Templates in the main project directory to store all of the project templates.
Open the settings.py file, and update the DIRS to refer to the Templates folder’s location.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Job Application</title>
<style>
table {
border: 8px outset;
border-radius: 10px;
border-spacing: 10px;
padding: 20px;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<h1 align="center">Job Application</h1>
<hr>
<h3 align="center">Please complete the form below to apply for a position with us.</h3>
<hr>
<br>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<table>
{{form.as_table}}
</table>
<br><br>
<div style="text-align:center">
<input type="submit" />
</div>
</form>
</body>
</html>
- First, we set the style of the table in the head tag.
- The heading for the form is then added inside the body tag using the HTML tags h1 and h4.
- The form will then be posted once it has been submitted by calling the form tag with the POST method.
- Add the enctype =”multipart/form-data” in the form tag otherwise, the form won’t work.
- Add the csrf_token within the form element to shield the form from cyberattacks and enable you to transmit the data securely.
- Next, use the form.as_table tag to render the form as a table.
- Lastly, add a submit button to submit the form.
Define View
To define the main logic for the job application form open the views.py file and add the code given below.
from django.shortcuts import render,HttpResponse
from .forms import ResumeForm
# Create your views here.
def jobapply(request):
if request.method == 'POST':
form = ResumeForm(request.POST,request.FILES)
if form.is_valid():
form.save()
return HttpResponse('Your Job Application is successfully submitted')
else:
form = ResumeForm()
context = {
'form':form,
}
return render(request, 'apply_form.html', context)
- First, import the ResumeForm from the forms.py and create a view named jobapply.
- Then, call the if statement and check whether the request method is POST.
- If yes, simply add a request.FILES along with the request.POST to the form method.
- Call the is_valid method to validate the input entered by the user, and if validation success calls the save() to save the data entered by users and return the HttpResponse.
- If the request method is GET, the user is presented with a blank job application form using the render() function.
Now, we must map the view with the URL in order to call it, thus we must create a file called urls.py in the app directory. Include the code below in it.
from django.urls import path
from . import views
urlpatterns = [
path('apply', views.jobapply, name='apply'),
]
Also, check: Get URL parameters in Django
Execute Django Application
To make a migration file that includes code for a model’s tabular schema type the below command in the terminal.
python manage.py makemigrations
To builds tables in accordance with the migration file’s schema execute the below command.
python manage.py migrate
To launch a development server type the below-given command in the terminal.
python manage.py runserver
By expanding the URL as shown below, we can access the job application form.
127.1.1.0/apply
It successfully opens the Django contact form that we create using the ModelForm which looks like this.
Now, fill out the form and click the submit button as shown below.
On successful submission of the form, we’ll get the HttpResponse as shown below.
Read: Compare two integers in Python Django
View submitted data from the Django admin interface
It will also save the data in the database. So, create a superuser and open the admin application and view it.
This is how you create a Form in Django using ModelForm class.
Download Django web form complete code
Conclusion
With this, we have successfully created a Django web form using the Form class and ModelForm class. Additionally, we have learned to add various controls like textbox, email, drop-down, datepicker, and radio buttons to the form.
We have also learned to upload the file in Django form and view the submitted form data on the admin interface.
Additionally, we have also covered the following topics.
- What is a web form
- Types of forms in Django
- How Django forms work
- Various form fields in Django
- How to create web form in Python Django using the Form class
- How to create web form in Python Django using ModelForm class
- How to use various controls like textbox, drop-down, email, datepicker, and radio buttons in Django
- How to upload files in Django form
You may also like to read the following Python Django tutorials.
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.