Django Forms are a powerful way to handle user input in web applications. They provide tools to generate HTML forms, validate data, and even save it to a database. A form in Django can be a class that defines the fields you want to display and the rules you want to enforce.
Characteristics
1. Automatic HTML Generation: Django generates HTML forms based on form classes.
2. Validation: Django provides built-in validations like required fields, email formats, and custom validations.
3. Integration with Models: Django can link forms directly to models (ModelForm), simplifying CRUD operations.
Example: Create a Contact Form
# forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=150, label="Name")
email = forms.EmailField(label="Email")
message = forms.CharField(widget=forms.Textarea, label="Message")
Explanation
CharField: A text input field.
EmailField: A field that validates email format.
widget=forms.Textarea: Customizes the message field to render as a <textarea> instead of a single-line input.Use Contact Form in View
# views.py
from django.shortcuts import render
from .forms import ContactForm
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process the form data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
return render(request, 'thank_you.html', {'name': name})
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
Call Contact Form View into Template
#contact.html
<!DOCTYPE html>
<html>
<head>
<title>Contact Us</title>
</head>
<body>
<h1>Contact Us</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</body>
</html>
Explanation
{{ form.as_p }}: Renders the form fields wrapped in <p> tags.{% csrf_token %}: Adds CSRF protection to the form.