More On Forms In Django and API In Forms

I hope you have read our earlier post on creating basic forms in django.In this post we will go in detail.

More On Fields In Forms 

Consider a below ContactForm class which we can be used to implement “contact me” functionality on a any personal website.

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea)
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

In the above case our form will have four fields: subject, message, sender and cc_myself. Also we have three types of available field types: CharField, EmailField and BooleanField.

Field data

Whenever the form data entered by the user in form is validated by calling is_valid(),the validated form data will be stored in form.cleaned_data dictionary.This data can be converted any time into python for the use of user.

For example in the above contact form cc_myself will be of boolean value.

Here’s how we can write the views.py file that will handle the form:

from django.core.mail import send_mail

if form.is_valid():
    subject = form.cleaned_data['subject']
    message = form.cleaned_data['message']
    sender = form.cleaned_data['sender']
    cc_myself = form.cleaned_data['cc_myself']

    recipients = ['info@example.com']
    if cc_myself:
        recipients.append(sender)

    send_mail(subject, message, sender, recipients)
    return HttpResponseRedirect('/thanks/')

send_mail is the inbuilt send API which can be used to send a email from sender to receiver.

Working with form templates

You can get your form into template by placing the form instance into the template context.

There are other output options though for the <label>/<input> pairs as following:

  • {{ form.as_table }} will render the form as table cells wrapped in <tr> tags
  • {{ form.as_p }} will render the form wrapped in <p> tags
  • {{ form.as_ul }} will render the form wrapped in <li> tags as unordered list.

So Here’s the output of {{ form.as_p }} for our ContactForm instance which we create for the above forms.py file.

<p><label for="id_subject">Subject:</label>
    <input id="id_subject" type="text" name="subject" maxlength="100" required /></p>
<p><label for="id_message">Message:</label>
    <textarea name="message" id="id_message" required></textarea></p>
<p><label for="id_sender">Sender:</label>
    <input type="email" name="sender" id="id_sender" required /></p>
<p><label for="id_cc_myself">Cc myself:</label>
    <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>

Bound and unbound forms

A Form instance created by developer will be either bound to a set of data or will be unbound.

  • If the form instance is bound to a set of data, it is capable of validating that data and rendering the form as HTML with the data displayed in the HTML.
  • If the form instance is unbound, it cannot do validation (because there’s no data to validate!), but it can still render the blank form as HTML.

We can create an unbound Form instance, simply by just instantiating the class as following:

f = ContactForm()

We can distinguish between bound and unbound form instances at runtime by checking the value of the form’s is_bound attribute as following:

f = ContactForm()
f.is_bound
False


f = ContactForm({'subject': 'hello'})
f.is_bound
True

Using forms to validate data

Form.is_valid():

The most important task of a Form object is to validate data means checking that whether the data entered by user in the form is valid or not.To check that we can run Form.is_valid() as following on a bound Form instance,it will return boolean answer depending on the whether the data is valid or not.

data = {'subject': 'hello',
        'message': 'Hi there',
        'sender': 'foo@example.com',
        'cc_myself': True}
f = ContactForm(data)

f.is_valid()
True

Now Let’s try with some invalid data and check what is_valid() will return.

data = {'subject': '',
        'message': 'Hi there',
        'sender': 'invalid email address',
        'cc_myself': True}
f = ContactForm(data)

f.is_valid()
False

rest of the form API we will discuss in the next post


So this is all about validating data using form API’s.

Leave a Comment

Your email address will not be published. Required fields are marked *