Django

Create a Django Form using forms.py and Display Submitted Values

๐Ÿ“Œ 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 fields
  • views.py โ†’ to process submitted values
  • template โ†’ 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.Form is the base class for creating forms
  • CharField is used for text input
  • label defines 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 correct
  • cleaned_data gives 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

  1. User opens form page
  2. Django creates blank StudentForm()
  3. User enters values and clicks Submit
  4. Data goes to request.POST
  5. Django validates form using is_valid()
  6. 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

  1. Add one more field for email
  2. Display values in table format
  3. Use form.as_table instead of form.as_p
  4. 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

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *