Skip to main content

Creating and Using Forms

In Django, forms are a simple way to collect data from users. They provide a structured way to validate this data and convert it into Python data types. In this tutorial, we will be discussing how to create and use forms in Django.

What Are Django Forms?

Before we dive into creating forms, let's briefly discuss what Django forms are. Django forms are a powerful tool that helps in creating HTML forms and handling submitted data. They help in validating the data, displaying form errors, and converting data into Python data types.

Creating a Simple Django Form

Let's start by creating a simple form. Below is an example of a basic Django form.

from django import forms

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

In the above code, we have created a form with three fields: name, email, and message.

  • name is a CharField, which is used for shorter strings.
  • email is an EmailField, which validates that the entered data is in the format of an email address.
  • message is also a CharField, but we are using a Textarea widget to get a larger input area in the HTML.

Using the Form in a View

Now, let's discuss how to use this form in a view. We will create a view that handles both the GET and POST methods.

from django.http import HttpResponseRedirect
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})

In the above code, we first check if the request method is POST. If it is, we create a form instance and populate it with data from the request. We call is_valid() to validate the data and if it's valid, we can process the data and redirect the user to a 'thanks' page.

If the request method is not POST (meaning the form has not been submitted), we create a new empty form and pass it into the template context.

Rendering the Form in a Template

Now, let's see how to render this form in a template. In Django, you can render forms as HTML with {{ form }}.

Here's an example template for our contact form:

<form method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>

In the above code, {% csrf_token %} is a security measure, and {{ form }} renders the form as HTML. The input element with type="submit" renders a submit button.

Conclusion

In this tutorial, we have discussed what Django forms are, how to create a simple form, and how to use this form in a view and a template. Django forms are a powerful tool that can handle most of the complexities of form handling for you. As you become more familiar with Django, you may want to explore model forms, which can save you even more time when working with data from models. Happy coding!