Creating Forms in Django
Django makes it easy to create and manage forms. Forms can be used for tasks like user input, data validation, and interacting with models. In this article, we'll explore how to create and use forms in Django with examples.
1. Introduction to Forms
Django provides a forms
module that allows you to create forms easily. Forms can be created manually or by using model forms that are tied to Django models.
2. Creating a Simple Form
To create a simple form, use Django's forms.Form
class. Here's an example:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(label='Your Name', max_length=100)
email = forms.EmailField(label='Your Email')
message = forms.CharField(label='Message', widget=forms.Textarea)
This form has three fields: name
, email
, and message
. The widget
attribute customizes the input field.
3. Rendering the Form in a Template
To display the form on a webpage, pass it to the template from the view:
# views.py
from django.shortcuts import render
from .forms import ContactForm
def contact_view(request):
form = ContactForm()
return render(request, 'contact.html', {'form': form})
In the template, render the form like this:
<form method="post" action="">
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
The as_p
method wraps each form field in a paragraph tag for basic formatting.
4. Handling Form Submission
Handle form data in the view by checking if the request is POST:
# 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 data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
print(f"Name: {name}, Email: {email}, Message: {message}")
return render(request, 'success.html')
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
The is_valid
method validates the input, and cleaned_data
contains the sanitized data.
5. Using Model Forms
Model forms allow you to create forms directly tied to Django models:
# models.py
from django.db import models
class Feedback(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
message = models.TextField()
# forms.py
from django.forms import ModelForm
from .models import Feedback
class FeedbackForm(ModelForm):
class Meta:
model = Feedback
fields = ['name', 'email', 'message']
Model forms automatically handle field validation based on the model definition.
6. Conclusion
In this article, we learned how to create forms in Django using forms.Form
and ModelForm
. Forms are a powerful feature in Django that make it easy to handle user input and validate data.