A form class in Django helps you create and manage web forms easily. It handles input fields, validation, and data processing.
0
0
Form class definition in Django
Introduction
When you want to collect user input on a website, like a contact form.
When you need to validate and clean data submitted by users.
When you want to reuse form logic across different pages.
When you want to connect form data to a database model.
When you want to display error messages automatically for invalid input.
Syntax
Django
from django import forms class MyForm(forms.Form): field_name = forms.FieldType(**options)
Define a form by creating a class that inherits from forms.Form.
Each form field is defined as a class attribute using Django's field types like CharField, EmailField, etc.
Examples
This form collects a name, email, and message from the user.
Django
from django import forms class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea)
This form is for user login with username and password fields.
Django
from django import forms class LoginForm(forms.Form): username = forms.CharField(max_length=50) password = forms.CharField(widget=forms.PasswordInput)
Sample Program
This defines a feedback form with three fields. It shows how to create the form and print each field's name and label.
Django
from django import forms class FeedbackForm(forms.Form): username = forms.CharField(max_length=30, label='Your Name') email = forms.EmailField(label='Your Email') feedback = forms.CharField(widget=forms.Textarea, label='Your Feedback') # Example usage in a Django view (not runnable here): # form = FeedbackForm(data=request.POST or None) # if form.is_valid(): # print(form.cleaned_data) # For demonstration, create an instance and print field names: form = FeedbackForm() for field in form: print(f"Field: {field.name}, Label: {field.label}")
OutputSuccess
Important Notes
Use label to set a friendly name for each field shown on the form.
Widgets control how the field looks in HTML, like Textarea for multi-line input.
Always validate form data before using it to avoid errors or security issues.
Summary
A Django form class defines fields and validation for user input.
It makes handling web forms easier and safer.
Use form classes to keep your code clean and reusable.