Introduction
Django forms help you collect and check user information easily and safely. They make building web pages that take input simple and reliable.
Jump into concepts and practice - no test required
Django forms help you collect and check user information easily and safely. They make building web pages that take input simple and reliable.
from django import forms class MyForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() # In your view: form = MyForm(request.POST or None) if form.is_valid(): # process form.cleaned_data
Django forms are Python classes that describe the fields you want.
You use is_valid() to check if the user input is good.
class ContactForm(forms.Form):
message = forms.CharField(widget=forms.Textarea)
email = forms.EmailField()class SignupForm(forms.Form): username = forms.CharField(max_length=30) password = forms.CharField(widget=forms.PasswordInput)
This example shows a form asking for a name. When submitted, it thanks the user by name.
from django import forms from django.http import HttpResponse from django.shortcuts import render class SimpleForm(forms.Form): name = forms.CharField(label='Your name', max_length=100) # A simple view to show and process the form def simple_form_view(request): if request.method == 'POST': form = SimpleForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] return HttpResponse(f'Thank you, {name}!') else: form = SimpleForm() return render(request, 'simple_form.html', {'form': form})
Django forms automatically handle HTML generation and validation.
They protect against common security issues like cross-site scripting.
You can customize forms to fit your exact needs easily.
Django forms make user input easy and safe.
They check data and show errors without extra work.
Using forms helps build better, more reliable web apps.
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
form = ContactForm({'name': 'Alice', 'email': 'alice@example.com'})
if form.is_valid():
cleaned_data = form.cleaned_data
else:
cleaned_data = None
print(cleaned_data)from django import forms
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField()
form = LoginForm({'username': 'user1'})
if form.is_valid():
print('Valid')
else:
print(form.errors)age. Which form field and validation approach is best to ensure this?