Python > Web Development with Python > Django > Forms
Django Form Example: Simple Contact Form
This example demonstrates a basic contact form in Django. It covers defining the form, rendering it in a template, and handling form submission.
Defining the Form (forms.py)
This code defines a Django form called The ContactForm
. It inherits from forms.Form
. Each field represents a form input:
name
: A character field for the user's name.email
: An email field for the user's email address.message
: A text area field for the user's message.label
argument specifies the human-readable label for each field, and the widget
argument defines the HTML input type used for the message
field (a text area in this case).
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)
Rendering the Form in a Template (template.html)
This template code renders the form. Let's break it down:
<form method="post">
: Specifies the form submission method (POST).{% csrf_token %}
: Adds a CSRF (Cross-Site Request Forgery) token for security. Crucial for POST requests in Django.{{ form.as_p }}
: Renders the form fields as paragraph elements (<p>
tags). Other options are form.as_table
and form.as_ul
.<button type="submit">Send</button>
: A submit button to send the form data.
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Send</button>
</form>
Handling Form Submission in a View (views.py)
This view function handles the contact form submission:
POST
(form submission).ContactForm
instance with the submitted data (request.POST
).form.is_valid()
to validate the form data.form.cleaned_data
. This data is safe to use because it has been validated and sanitized.send_mail
function. You'll need to configure your email settings.redirect('success')
). You'll need to define a URL pattern named 'success'.ContactForm
instance.contact.html
template, passing the form instance as context.
from django.shortcuts import render, redirect
from .forms import ContactForm
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process the form data (e.g., send an email)
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
# Add code to send an email here (using Django's send_mail function)
# For example:
# from django.core.mail import send_mail
# send_mail(
# 'Contact Form Submission',
# f'Name: {name}\nEmail: {email}\nMessage: {message}',
# 'from@example.com',
# ['to@example.com'],
# fail_silently=False,
# )
return redirect('success') # Redirect to a success page
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
URL Configuration (urls.py)
This code snippet showcases how to configure the URLs to your contact and success views using Django's URL dispatcher.
from django.urls import path
from . import views
urlpatterns = [
path('contact/', views.contact, name='contact'),
path('success/', views.success, name='success'), #Example for redirection after success
]
Success View (views.py)
Simple view to render success page.
from django.shortcuts import render
def success(request):
return render(request, 'success.html')
Success Template (success.html)
Very basic template for success page.
<h1>Success!</h1>
<p>Your message has been sent.</p>
Real-Life Use Case
This contact form example can be used on any website to allow users to send messages to the website administrator or support team. It's a fundamental building block for user interaction.
Best Practices
form.is_valid()
before processing it.form.cleaned_data
to access the validated data.django.core.mail
) to send emails.
Interview Tip
When asked about Django forms in an interview, be prepared to discuss the following:
forms.Form
or forms.ModelForm
.form.is_valid()
and form.cleaned_data
.
When to Use Them
Use Django forms whenever you need to handle user input in your web application. This includes:
Alternatives
While Django forms are a powerful tool, alternatives exist:
Pros
Benefits of using Django forms:
ModelForm
allows creating forms directly from Django models.
Cons
Potential drawbacks of using Django forms:
FAQ
-
How do I add validation to a form field?
You can add validation by specifying validators in the form field definition. Django provides several built-in validators (e.g.,validators=[MaxValueValidator(100)]
). You can also create custom validators. -
How do I customize the appearance of a form?
You can customize the appearance of a form using CSS. You can also create custom form templates to have more control over the HTML structure. -
What is CSRF protection?
CSRF (Cross-Site Request Forgery) protection is a security measure that prevents malicious websites from making unauthorized requests on behalf of a logged-in user. Django provides built-in CSRF protection, which you should always use for POST requests.