Welcome back to CodeYourCraft! Today, we're going to dive into creating forms in Django, a powerful Python web framework. Forms are essential for collecting user input and are crucial in most web applications. Let's get started! π―
In Django, a form is an object that represents user input. It simplifies handling and validating user input, and makes it easy to create HTML forms for user interaction.
Let's create a simple form for collecting a user's name.
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='What is your name?', max_length=100)Here, we've created a form called NameForm with a single CharField for inputting a user's name.
Now, let's use our form in a view.
from django.shortcuts import render
from .forms import NameForm
def form_view(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
print(f'Hello, {form.cleaned_data["your_name"]}!')
else:
form = NameForm()
return render(request, 'form.html', {'form': form})In this view, we check if the request is a POST request. If it is, we create a form instance with the posted data. We then check if the form is valid, and if so, print a greeting with the user's name. If the request is not a POST request, we create an empty form.
Next, let's create a template for our form.
<html>
<body>
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
</body>
</html>Here, we render the form in our template using the {{ form }} tag. We also include a CSRF token for security purposes.
Django automatically validates our form based on the field types we've defined. For example, the CharField for the user's name requires a string input of up to 100 characters.
Django offers various field types, including EmailField, DateTimeField, and FileField. You can also create forms using Django's modelforms and formsets for more complex scenarios.
Which Python package do we import to create forms in Django?
That's it for today! In the next lesson, we'll dive deeper into advanced forms and form validation in Django. Until then, happy coding! π