Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Forms are an important component of any web application that relies on user input. It doesn't matter if we're filling out login forms, entering survey information, or creating blog articles and comments; we would always need Django forms.
Forms offer a variety of ways to connect with users. The process of handling forms, on the other hand, is complicated. Forms accept input from the user, posing a significant security risk. We can imagine forms as an open door due to which we will require some security measures to protect it. The general rule is never to trust the user input or, worse, malicious attackers preying on naive users. We must ensure that the user's data is taken care of and field validation is taken into account; therefore, caution is essential.
What are Forms in Django?
Django forms are a complex collection of HTML forms that can be produced using Python and support all of the features of HTML forms in a Python-friendly manner. This blog covers making a basic form with Form Attributes and Fields. In Django, building a form is quite similar to creating a model in which we must specify which fields will be present in the form and of what kind. For instance, to fill out a registration form, we might need to know the first name (CharField), the roll number (IntegerField), and so on.
Why are Django Forms used?
In a web application, dealing with HTML forms can be a difficult task: ideally, we have a consistent way of rendering input fields and processing the data that's been inputted. Forms in Django are a framework that allows us to do it precisely. Django comes with specific standard ways of generating forms with various types of inputs; it performs field validation and handles some of the security concerns. Forms in Django move the data in and out of the models.
Handling Process of Django Forms
Django's form handling utilizes most of the same approaches. For example, the view receives a request, conducts any necessary actions, such as reading data from the models, and then creates and returns an HTML page (from a template, in which we pass the context containing the data to be displayed). What complicates things further is that the server must process data provided by the user and redisplay the page if any problems occur.
A flowchart depicting how Django handles form requests
The following are the primary functions of handling the process of forms in Django:
The default form will be displayed the first time the user requests it.
If we establish a new record, the form may include blank fields or pre-populated with default values (e.g., changing a record or having proper default initial values).
Since it isn't linked with any user-entered data at this point, the form is referred to as unbound (though it may have initial values).
2. Data from a submit request is received and bound to the form.
When we bind data to a form, we ensure that the user-entered data and any mistakes are available when the form is re-displayed.
3. Validate and clean the data.
Cleaning the data sanitizes the input (for example, deleting invalid characters that may be used to send harmful stuff to the server). It turns it to Python types that are consistent.
Validation ensures that the values are appropriate for the field (e.g., that values are within the correct date range, aren't too short or lengthy, and so on).
4. Re-display the form with user populated values and error warnings for the problem fields if any invalid data exists.
5. Perform the needed actions if all data is valid (e.g., send an email, save the data, upload a file, return the search result, etc.)
6. Redirect the user to another page once all the actions have been completed.
Sample Example of Django Forms
We will first create a folder ‘Django_Forms’. Inside the folder, we will begin our project formTest.
django-admin startproject formTest
We will then navigate into the project folder.
cd formTest
We will run the following command for the Django form application.
python3 manage.py startapp formTestApp
Create a ‘templates’ folder within your 'formTest' folder, then a 'formTestApp' folder within that folder, and add ‘index.html’ and ‘form_page.html’ files within that folder.
Project Structure:
Django_Forms/formTest
|
|--------formTest
| |--------settings.py
| |--------urls.py
|
|--------formTestApp
| |--------forms.py
| |--------views.py
|
|--------templates/formTestApp
| |--------index.html
| |--------form_page.html
|
|--------manage.py
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CodingNinjas</title>
<!-- CSS only Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>Welcome to Django Forms</h1>
<br/>
<h2>Navigate to '/formpage' to check out the working of Django forms</h2>
</div>
</div>
</body>
</html>
We now design the form fields that our users will see and fill out.
forms.py:
from django import forms
# Create the FormName class
class FormName(forms.Form):
name = forms.CharField()
email = forms.EmailField()
text = forms.CharField(widget = forms.Textarea)
You can also try this code with Online Python Compiler
from django.shortcuts import render
from . import forms
# Create your views here.
def index(request):
return render(request, 'formTestApp/index.html')
def form_name_view(request):
form = forms.FormName()
#Check to see if we are getting a POST request back
if request.method == "POST":
# if post method = True
form = forms.FormName(request.POST)
# Then we check to see if the form is valid (this is an automatic validation by Django)
if form.is_valid():
# if form.is_valid == True then do something
print("Form validation successful! See console for information:")
print("Name: "+form.cleaned_data['name'])
print("email: "+form.cleaned_data['email'])
print("message: "+form.cleaned_data['text'])
return render(request, 'formTestApp/form_page.html', {'form': form})
You can also try this code with Online Python Compiler
We will add the following changes to the ‘settings.py’ file:
Then, we will run the following command, and we will get the desired output.
python3 manage.py runserver
Output(Homepage)
Output(Form Page)
Frequently Asked Questions
What is the work of Forms in Django? Forms in Django performs these tasks: 1. Read the user's input. 2. Validate the user input. 3. The input is converted to Python data types/objects. 4. Preparing and reorganizing data for rendering 5. Making HTML forms for data 6. Receiving and processing the client's submitted forms and data
How are Django Forms different from Django ModelForm? Django ModelForm converts fields into database types, whereas Django Forms convert fields into Python types. Django ModelForm is the class that directly converts a model into a Django form.
Key Takeaways
In this blog, we have learned the concepts of Forms in Django. All of the work done by Django forms can be done using advanced HTML, but Django makes it easier and more efficient, especially when it comes to validation. Once we have mastered the Django forms, we will never go back to HTML forms.