๐ Introduction
In Django, forms can be created in two ways:
- HTML forms directly in templates
- Django forms using
forms.py
Using forms.py is better because it provides:
- Cleaner code
- Easy validation
- Reusable form structure
In this program, we will:
- Create a form in
forms.py - Display it in a template
- Submit values
- Show submitted data on the same page
๐ฏ Program Statement
๐ Create a Django form using forms.py and display submitted values.
๐ง Concept Overview
This program uses:
forms.pyโ to define form fieldsviews.pyโ to process submitted valuestemplateโ to display form and output
โ๏ธ Step 1: Create Form Class
๐ File: forms.py
๐น Path:
myproject/myapp/forms.py
๐น Code:
from django import forms
class StudentForm(forms.Form):
name = forms.CharField(label='Enter Name', max_length=100)
course = forms.CharField(label='Enter Course', max_length=100)
๐ง Explanation
forms.Formis the base class for creating formsCharFieldis used for text inputlabeldefines field label shown in form
โ๏ธ Step 2: Create View
๐ File: views.py
๐น Path:
myproject/myapp/views.py
๐น Code:
from django.shortcuts import render
from .forms import StudentForm
def student_form(request):
submitted_data = None
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
submitted_data = {
'name': form.cleaned_data['name'],
'course': form.cleaned_data['course']
}
else:
form = StudentForm()
return render(request, 'student_form.html', {
'form': form,
'data': submitted_data
})
๐ง Explanation
- If page opens first time โ blank form shown
- If form submitted โ data comes through
request.POST is_valid()checks whether data is correctcleaned_datagives validated values
โ๏ธ Step 3: URL Mapping
๐ File: urls.py
๐น Path:
myproject/myproject/urls.py
๐น Code:
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('student-form/', views.student_form, name='student_form'),
]
โ๏ธ Step 4: Create Template
๐ File: student_form.html
๐น Path:
myproject/templates/student_form.html
๐น Code:
<!DOCTYPE html>
<html>
<head>
<title>Django Form Example</title>
</head>
<body>
<h1>Student Form</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
<hr>
{% if data %}
<h2>Submitted Values</h2>
<p><strong>Name:</strong> {{ data.name }}</p>
<p><strong>Course:</strong> {{ data.course }}</p>
{% endif %}
</body>
</html>
๐ง Explanation
method="post"sends form data securely{% csrf_token %}is required for POST forms in Django{{ form.as_p }}displays form fields inside paragraphs- Submitted values are shown below the form
โ๏ธ Step 5: Run Server
python manage.py runserver
๐ Step 6: Output
Open:
๐ http://127.0.0.1:8000/student-form/
โ On page load:
- Form with Name and Course fields appears
โ After submission:
Example input:
- Name: Nyra
- Course: MCA
Output:
Submitted Values Name: Nyra Course: MCA
๐ง How It Works
- User opens form page
- Django creates blank
StudentForm() - User enters values and clicks Submit
- Data goes to
request.POST - Django validates form using
is_valid() - Valid data is displayed in template
๐ฅ Key Concepts
Form Class
class StudentForm(forms.Form):
Creates Django form structure.
POST Data
form = StudentForm(request.POST)
Used when form is submitted.
Validation Check
if form.is_valid():
Checks if submitted data is valid.
Cleaned Data
form.cleaned_data['name']
Returns validated user input.
โ ๏ธ Common Errors
โ Forgot forms.py
Create the file manually if it does not exist:
myproject/myapp/forms.py
โ Forgot CSRF token
If {% csrf_token %} is missing, Django will show CSRF verification failed error.
โ Import error
Use correct import in views.py:
from .forms import StudentForm
โ is_valid() not used
Without is_valid(), cleaned data cannot be accessed safely.
โ Form not displaying
Check:
{{ form.as_p }}
or use {{ form.as_table }} / {{ form.as_ul }}
๐งช Practice Questions
- Add one more field for email
- Display values in table format
- Use
form.as_tableinstead ofform.as_p - Add age field and display all submitted values
๐ค Viva Questions & Answers
1. What is forms.py in Django?
forms.py is a Python file used to define Django forms. It helps create reusable, validated, and structured input forms.
2. What is the advantage of using Django forms instead of plain HTML forms?
Django forms provide built-in validation, cleaner code, and easy integration with views and templates. They also reduce manual form handling.
3. What is forms.Form?
forms.Form is the base class used to create a form in Django. We define fields inside this class.
4. What is CharField in Django forms?
CharField is used to accept text input from the user. It is commonly used for name, course, city, etc.
5. Why do we use request.POST?
request.POST contains the form data submitted through POST method. It is used to initialize the form with user input.
6. What is is_valid()?
is_valid() checks whether the form data satisfies all validation rules. Only after this, cleaned data should be accessed.
7. What is cleaned_data?
cleaned_data contains validated and cleaned input values from the form. It is safer than directly using raw POST data.
8. Why is {% csrf_token %} required?
It protects the form from CSRF attacks. Django requires it in all POST forms for security.
9. What is form.as_p?
form.as_p displays the form fields wrapped inside paragraph tags. It is a quick way to render the form.
10. Can we display submitted values on the same page?
Yes, the view can send submitted values back to the same template, and the template can display them conditionally.
๐ Next Post: Create a POST Form to Add Two Numbers and Display Result
๐ Back to List: Django Programs (60 Questions with Solutions)
Further Reading
Introduction to Django Framework and its Features
Examples of Array Functions in PHP
Registration Form Using PDO in PHP
Inserting Information from Multiple CheckBox Selection in a Database Table in PHP
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
