Creating forms with Django
Let's start by building the form to share posts. Django has a built-in forms framework that allows you to create forms in an easy manner. The forms framework allows you to define the fields of your form, specify how they have to be displayed, and indicate how they have to validate input data. The Django forms framework offers a flexible way to render forms and handle the data.
Django comes with two base classes to build forms:
- Form: Allows you to build standard forms
- ModelForm: Allows you to build forms tied to model instances
First, create a forms.py file inside the directory of your blog application and make it look like this:
from django import forms
class EmailPostForm(forms.Form):
name = forms.CharField(max_length=25)
email = forms.EmailField()
to = forms.EmailField()
comments = forms.CharField(required=False,
widget=forms.Textarea)
This is your first Django form. Take a look at the code. We have created a form by inheriting the base Form class. We use different field types for Django to validate fields accordingly.
Forms can reside anywhere in your Django project. The convention is to place them inside a forms.py file for each application.
The name field is CharField. This type of field is rendered as an <input type="text"> HTML element. Each field type has a default widget that determines how the field is rendered in HTML. The default widget can be overridden with the widget attribute. In the comments field, we use a Textarea widget to display it as a <textarea> HTML element instead of the default <input> element.
Field validation also depends on the field type. For example, the email and to fields are EmailField fields. Both fields require a valid email address, otherwise, the field validation will raise a forms.ValidationError exception and the form will not validate. Other parameters are also taken into account for form validation: we define a maximum length of 25 characters for the name field and make the comments field optional with required=False. All of this is also taken into account for field validation. The field types used in this form are only a part of Django form fields. For a list of all form fields available, you can visit https://docs.djangoproject.com/en/2.0/ref/forms/fields/.