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 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.

The 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:

  • It checks if the request method is POST (form submission).
  • If it's a POST request, it creates a ContactForm instance with the submitted data (request.POST).
  • It calls form.is_valid() to validate the form data.
  • If the form is valid, it retrieves the cleaned data from form.cleaned_data. This data is safe to use because it has been validated and sanitized.
  • In a real application, you would process the data here (e.g., send an email, save to a database). The example includes commented-out code to send an email using Django's send_mail function. You'll need to configure your email settings.
  • After processing, it redirects the user to a success page (redirect('success')). You'll need to define a URL pattern named 'success'.
  • If it's not a POST request (e.g., initial page load), it creates an empty ContactForm instance.
  • Finally, it renders the 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

  • Always use CSRF protection for POST requests.
  • Validate form data using form.is_valid() before processing it.
  • Use form.cleaned_data to access the validated data.
  • Handle errors gracefully and provide helpful feedback to the user.
  • Sanitize user input to prevent security vulnerabilities (e.g., cross-site scripting). Django forms provide built-in protection, but always be mindful.
  • Consider using Django's built-in email functionality (django.core.mail) to send emails.

Interview Tip

When asked about Django forms in an interview, be prepared to discuss the following:

  • The purpose of forms (handling user input, validation).
  • How to define forms using forms.Form or forms.ModelForm.
  • How to render forms in templates.
  • How to handle form submissions in views.
  • The importance of CSRF protection.
  • The use of 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:

  • Contact forms
  • Registration forms
  • Login forms
  • Data entry forms
  • Search forms

Alternatives

While Django forms are a powerful tool, alternatives exist:

  • Django REST Framework serializers: Suitable for handling API requests and data serialization/deserialization.
  • HTML forms with custom JavaScript validation: Provides more control over the front-end but requires more manual implementation.
  • Third-party form libraries: Offer specialized features or UI components.

Pros

Benefits of using Django forms:

  • Security: Built-in CSRF protection and data sanitization.
  • Validation: Easy to validate user input with built-in validators.
  • Rendering: Simple to render forms in templates.
  • Abstraction: Provides a high-level abstraction for handling form logic.
  • Model Integration: ModelForm allows creating forms directly from Django models.

Cons

Potential drawbacks of using Django forms:

  • Overhead: Can be overkill for very simple forms.
  • Customization: Customizing the appearance can sometimes be challenging.

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.