Forms in Python


In [1]:
from pprint import pprint
from organizer.forms import TagForm

The Very Basics


In [2]:
tform = TagForm()

In [3]:
tform.is_bound  # no data


Out[3]:
False

In [4]:
tform.is_valid()  # data is not valid


Out[4]:
False

Adding Data to the Mix


In [5]:
tform = TagForm({})

In [6]:
tform.is_bound


Out[6]:
True

In [7]:
try:
    tform.cleaned_data
except AttributeError as e:
    print(e)


'TagForm' object has no attribute 'cleaned_data'

In [8]:
tform.is_valid()


Out[8]:
False

In [9]:
tform.cleaned_data  # created by is_valid()


Out[9]:
{}

In [10]:
tagdata = {
    'name':'new tag',
    'slug':'new_tag',
}
tform = TagForm(tagdata)

In [11]:
tform.is_bound


Out[11]:
True

In [12]:
tform.is_valid()


Out[12]:
True

In [13]:
tform.cleaned_data


Out[13]:
{'name': 'new tag', 'slug': 'new_tag'}

Handling Validation Errors


In [14]:
# from the TagForm above
tform.errors


Out[14]:
{}

In [15]:
tform = TagForm(tagdata)
tform.errors


Out[15]:
{}

In [16]:
tform.cleaned_data  # created by access to errors attribute


Out[16]:
{'name': 'new tag', 'slug': 'new_tag'}

In [17]:
errordata = {
    'name':None,
    'slug':'new_tag',
}
tform = TagForm(errordata)

In [18]:
tform.is_bound


Out[18]:
True

In [19]:
tform.is_valid()


Out[19]:
False

In [20]:
tform.cleaned_data


Out[20]:
{'slug': 'new_tag'}

In [21]:
tform.errors


Out[21]:
{'name': ['This field is required.']}

In [22]:
# normally lazily evaluates
# pprint helps make this much clearer
# (try it without pprint yourself!)
pprint(tform.errors.as_data())


{'name': [ValidationError(['This field is required.'])]}

In [23]:
errordata2 = {
    'name':'abcdefghijklmnopqrstuvwxyzabcdef',
    'slug':'new_tag',
}

In [24]:
len(errordata2['name'])


Out[24]:
32

In [25]:
tform = TagForm(errordata2)
tform.is_valid()


Out[25]:
False

In [26]:
tform.cleaned_data


Out[26]:
{'slug': 'new_tag'}

In [27]:
tform.errors


Out[27]:
{'name': ['Ensure this value has at most 31 characters (it has 32).']}