Django Forms Defining a Django form from scratch (with widgets)


Forms can be defined, in a similar manner to models, by subclassing django.forms.Form.
Various field input options are available such as CharField, URLField, IntegerField, etc.

Defining a simple contact form can be seen below:

from django import forms

class ContactForm(forms.Form):
    contact_name = forms.CharField(
        label="Your name", required=True,
        widget=forms.TextInput(attrs={'class': 'form-control'}))
    contact_email = forms.EmailField(
        label="Your Email Address", required=True,
        widget=forms.TextInput(attrs={'class': 'form-control'}))
    content = forms.CharField(
        label="Your Message", required=True,
        widget=forms.Textarea(attrs={'class': 'form-control'}))

Widget is Django's representation of HTML user-input tags and can be used to render custom html for form fields (eg: as a text box is rendered for the content input here)

attrs are attributes that will be copied over as is to the rendered html for the form.

Eg: content.render("name", "Your Name") gives

<input title="Your name" type="text" name="name" value="Your Name" class="form-control" />