Django

Create a Feedback Form with Validations such as Required Fields and Email Format

๐Ÿ“Œ Introduction

Validation is used to ensure that the user enters correct and complete data.

In this program, we will create a feedback form with:

  • required fields
  • email format validation
  • minimum message length
  • error display in the form

This program helps students understand:

  • form validation
  • required fields
  • built-in validators
  • error messages in Django forms

๐ŸŽฏ Program Statement

๐Ÿ‘‰ Create a feedback form with validations such as required fields and email format.


๐Ÿง  Concept

This program uses:

  • forms.py for form definition and validation rules
  • views.py for processing submitted data
  • template for displaying form, errors, and submitted summary

โš™๏ธ Step 1: Create Form with Validations

๐Ÿ“ File: forms.py

๐Ÿ”น Path:

myproject/myapp/forms.py

๐Ÿ”น Code:

from django import forms

class FeedbackValidationForm(forms.Form):
name = forms.CharField(
label='Enter Your Name',
max_length=100,
required=True
)

email = forms.EmailField(
label='Enter Your Email',
required=True
)

subject = forms.CharField(
label='Enter Subject',
max_length=150,
required=True
)

message = forms.CharField(
label='Enter Feedback',
required=True,
min_length=10,
widget=forms.Textarea(attrs={'rows': 4, 'cols': 40})
)

๐Ÿง  Explanation

  • required=True makes the field compulsory
  • EmailField checks correct email format
  • min_length=10 ensures feedback message is meaningful
  • Textarea is used for long feedback

โš™๏ธ Step 2: Create View

๐Ÿ“ File: views.py

๐Ÿ”น Path:

myproject/myapp/views.py

๐Ÿ”น Code:

from django.shortcuts import render
from .forms import FeedbackValidationForm

def feedback_validation(request):
submitted_data = None

if request.method == 'POST':
form = FeedbackValidationForm(request.POST)
if form.is_valid():
submitted_data = {
'name': form.cleaned_data['name'],
'email': form.cleaned_data['email'],
'subject': form.cleaned_data['subject'],
'message': form.cleaned_data['message']
}
else:
form = FeedbackValidationForm()

return render(request, 'feedback_validation.html', {
'form': form,
'data': submitted_data
})

๐Ÿง  Explanation

  • Blank form is shown on first load
  • On POST submission, Django validates the fields automatically
  • If the form is valid, submitted values are shown
  • If invalid, errors are displayed in the template

โš™๏ธ 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('feedback-validation/', views.feedback_validation, name='feedback_validation'),
]

โš™๏ธ Step 4: Create Template

๐Ÿ“ File: feedback_validation.html

๐Ÿ”น Path:

myproject/templates/feedback_validation.html

๐Ÿ”น Code:

<!DOCTYPE html>
<html>
<head>
<title>Feedback Form with Validation</title>
</head>
<body>

<h1>Feedback Form with Validation</h1>

<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit Feedback</button>
</form>

<hr>

{% if data %}
<h2>Submitted Feedback Summary</h2>
<p><strong>Name:</strong> {{ data.name }}</p>
<p><strong>Email:</strong> {{ data.email }}</p>
<p><strong>Subject:</strong> {{ data.subject }}</p>
<p><strong>Message:</strong> {{ data.message }}</p>
{% endif %}

</body>
</html>

๐Ÿง  Explanation

  • If any field is empty, Django shows validation error automatically
  • If email format is invalid, EmailField shows an email error
  • If message is too short, min_length triggers an error

โš™๏ธ Step 5: Run Server

python manage.py runserver

๐ŸŒ Step 6: Output

Open:

๐Ÿ‘‰ http://127.0.0.1:8000/feedback-validation/

โœ… Valid Input Example:

  • Name: Juhi
  • Email: juhi@gmail.com
  • Subject: Website Feedback
  • Message: This website is very helpful for students.

โœ… Output:

Submitted Feedback Summary
Name: Juhi
Email: juhi@gmail.com
Subject: Website Feedback
Message: This website is very helpful for students.

โŒ Invalid Input Example 1:

  • Email: abc

Output:

Enter a valid email address.

โŒ Invalid Input Example 2:

  • Message: Good

Output:

Ensure this value has at least 10 characters.

โŒ Invalid Input Example 3:

  • Leave name empty

Output:

This field is required.

๐Ÿง  How It Works

  1. User opens the feedback form
  2. Enters values and submits form
  3. Django checks validation rules automatically
  4. If data is valid, summary is shown
  5. If data is invalid, error messages appear near fields

๐Ÿ”ฅ Key Concepts

Required Fields

required=True

Ensures the field cannot be left empty.


Email Validation

forms.EmailField()

Checks that the entered email is in valid format.


Minimum Length

min_length=10

Ensures the message is not too short.


Built-in Error Display

{{ form.as_p }}

Automatically displays field errors in the template.


โš ๏ธ Common Errors

โŒ Forgot required=True

Then empty input may not be blocked as expected.


โŒ Used CharField for email

This will not validate email format automatically.


โŒ Forgot min_length

Short messages like โ€œokโ€ will be accepted.


โŒ Forgot CSRF token

POST form will fail with security error.


โŒ Imported wrong form in views.py

Use:

from .forms import FeedbackValidationForm

๐Ÿงช Practice Questions

  1. Add phone number field with validation
  2. Set minimum length of subject to 5
  3. Add maximum length to feedback message
  4. Display custom error messages
  5. Add optional city field

๐ŸŽค Viva Questions & Answers

1. What is form validation in Django?

Form validation is the process of checking whether the user input is correct, complete, and acceptable before processing it.

2. What is the use of required=True?

It makes the form field compulsory. If the user leaves it empty, Django shows an error.

3. Why is EmailField used instead of CharField?

EmailField automatically checks that the entered value follows a valid email format. CharField does not do this.

4. What is min_length in Django forms?

min_length defines the minimum number of characters required in a field. It helps reject very short input.

5. What happens if a form is invalid?

The form is not processed, and Django displays error messages for the fields that failed validation.

6. Where are validation rules usually written?

Validation rules are usually written in forms.py while defining the fields.

7. Does Django automatically show form errors?

Yes, when using {{ form.as_p }} or similar rendering methods, field errors are displayed automatically.

8. Why are validations important in forms?

Validations ensure data quality, prevent incorrect input, and improve reliability of the application.

9. Can we add more advanced validation later?

Yes, Django supports custom validation methods, including clean() and field-specific cleaning methods.


๐Ÿ‘‰ Next Post: Create an Age Validation Form that Checks Eligibility (age โ‰ฅ 18)
๐Ÿ‘‰ 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 *