In Django, a form is a fundamental component of building web applications that handle user input. Django provides a built-in Form class, which allows you to define and handle HTML forms in a simplified and efficient manner.
Here's an overview of working with forms in Django:
Creating a Form Class:
To define a form in Django, you need to create a subclass of django.forms.Form. In the form class, you define fields and their corresponding validation rules.
from django import forms
class MyForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput)
Rendering the Form in a View:
In your view function or class, you instantiate the form class and pass it to the template for rendering.
from django.shortcuts import render
def my_view(request):
form = MyForm()
return render(request, 'my_template.html', {'form': form})
Displaying the Form in a Template:
In your template file, you can render the form fields using Django template tags.
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
Handling Form Submission:
When the form is submitted, you need to process the submitted data and perform any necessary validation.
def my_view(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
# Process the form data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
# ...
# Perform further actions
# ...
else:
form = MyForm()
return render(request, 'my_template.html', {'form': form})
In the above example, the is_valid() method is used to validate the submitted form data. If the form is valid, you can access the cleaned and validated data using the cleaned_data attribute.