Django is a high-level Python Web framework that enables us to create robust dynamic web applications. In the process of building web applications, a significant aspect is the creation of forms which enables users to interact with the web applications. Django provides a powerful form library which simplifies the task of creating forms, validating data, and rendering forms in templates.
Firstly, to use Django forms, it’s necessary to import the forms module by including the statement `from django import forms` at the beginning of your Python file. Then, you can create a form by creating a class that inherits from the Form class, such as:
```
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=50)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
```
In the given example, the ContactForm class indicates a form with three fields. The forms come with built-in validations, for instance, EmailField ensures that the input is a valid email.
Next, to display the form in a template, Django gives `{{ form.as_p }}`, `{{ form.as_table }}` or `{{ form.as_ul }}` which respectively displays the form fields enclosed within `
`, `
`, and `` tags. Further customization can also manually be performed.
Processing the form data when the user submits the form is an important step. Typically, this is done within Django view function or method. Here the `is_valid()` function is used to check if the submitted data is valid. If it is, you can access the cleaned and validated data by using the `cleaned_data` attribute. An example would be:
```
def contact_us(request):
if request.method == ‘POST’:
form = ContactForm(request.POST)
if form.is_valid():
name = form.cleaned_data[‘name’]
email = form.cleaned_data[‘email’]
message = form.cleaned_data[‘message’]
else:
form = ContactForm()
return render(request, ‘contact.html’, {‘form’: form})
```
In the above example, once all fields have passed the validations, the cleaned data is stored as dictionary format which can be accessed as shown.
Remember, Django also provides Model forms that are a subclass of forms which allow you to automatically generate a form from a Django model. It’s a good way to quickly build forms if you have model already defined.
To prepare this answer, I used the [official Django documentation](https://docs.djangoproject.com/en/3.2/topics/forms/) which provides a comprehensive overview of working with Django forms.
Finally, keep in mind that while Django forms provide a good level of abstraction, making form handling much easier, learning to work with them effectively will require practice.
Simply generate articles to optimize your SEO
DinoGeek offers simple articles on complex technologies
Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr