Welcome to the third lesson in our Django Tutorial series! Today, we'll dive into an essential aspect of Django - Form Rendering in Templates. By the end of this lesson, you'll be able to create, render, and process forms in your Django applications.
Forms in Django are used to collect user input. They simplify the process of handling user-submitted data and validating it according to specific rules.
First, let's create a form for a simple contact form. In your project directory, navigate to myproject/forms.py.
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)π‘ Pro Tip: Always give meaningful names to your fields. This makes it easier to understand the form structure.
Next, let's create a template for our contact form. Navigate to myproject/templates/contact_form.html.
<!DOCTYPE html>
<html>
<head>
<title>Contact Us</title>
</head>
<body>
<h1>Contact Form</h1>
<form method="post">
{% csrf_token %}
{{ form.as_form }}
<button type="submit">Submit</button>
</form>
</body>
</html>π‘ Pro Tip: Always include the CSRF token in your forms to protect against Cross-Site Request Forgery (CSRF).
Finally, let's create a view to handle form submissions. Navigate to myproject/views.py.
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 form data here
pass
else:
form = ContactForm()
return render(request, 'contact_form.html', {'form': form})π‘ Pro Tip: Always check if the request method is POST when handling form submissions.
In the previous example, we didn't process the form data. Let's see how we can validate and process form data.
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# process form data here
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
# send email or save data to database
pass
else:
form = ContactForm()
return render(request, 'contact_form.html', {'form': form})π‘ Pro Tip: Always validate and process form data using form.is_valid() and form.cleaned_data.
What does `form.is_valid()` return in Django forms?
That's it for today! In the next lesson, we'll learn how to handle form errors in Django. Stay tuned! π