Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Forms in Django

What are Forms?

Forms are a way of collecting user input in a web application. They allow users to submit data to the server, such as filling out a registration form, creating a blog post, or updating their profile information. In Django, forms are easy to create and handle, which makes it a powerful framework for web development.

Creating a Simple Form

To create a form in Django, you typically start by defining a form class. Here's a basic 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(widget=forms.Textarea, label='Your message')

Rendering the Form in a Template

Once you've created a form class, you can render it in a template. Here's how you can do it:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Send</button>
</form>

Handling Form Submission

When a form is submitted, you need to handle the data in your view. Here's an example of how you can do this:

from django.shortcuts import render
from .forms import ContactForm

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process the data in form.cleaned_data
            return HttpResponseRedirect('/thanks/')
    else:
        form = ContactForm()

    return render(request, 'contact.html', {'form': form})

Form Validation

Form validation is a crucial part of handling user input. Django provides several ways to validate forms:

  • Built-in validators such as forms.EmailField() which ensures the input is a valid email.
  • Custom validation methods within the form class.

Here's an example of custom validation:

class ContactForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)

    def clean_name(self):
        name = self.cleaned_data.get('name')
        if "badword" in name:
            raise forms.ValidationError("Bad word detected!")
        return name

Conclusion

In this tutorial, we've covered the basics of creating and handling forms in Django. We discussed how to create a simple form, render it in a template, handle form submissions, and validate form data. Forms are an essential part of web development, and Django provides powerful tools to make form handling straightforward and efficient.