/tests/regressiontests/forms/tests/forms.py
Python | 1724 lines | 1683 code | 16 blank | 25 comment | 12 complexity | 17beefea3cf04a0dedfb41b9e743e8a2 MD5 | raw file
Possible License(s): BSD-3-Clause
Large files files are truncated, but you can click here to view the full file
- # -*- coding: utf-8 -*-
- import datetime
- from decimal import Decimal
- import re
- import time
- from django.core.files.uploadedfile import SimpleUploadedFile
- from django.forms import *
- from django.http import QueryDict
- from django.template import Template, Context
- from django.utils.datastructures import MultiValueDict, MergeDict
- from django.utils.safestring import mark_safe
- from django.utils.unittest import TestCase
- class Person(Form):
- first_name = CharField()
- last_name = CharField()
- birthday = DateField()
- class PersonNew(Form):
- first_name = CharField(widget=TextInput(attrs={'id': 'first_name_id'}))
- last_name = CharField()
- birthday = DateField()
- class FormsTestCase(TestCase):
- # A Form is a collection of Fields. It knows how to validate a set of data and it
- # knows how to render itself in a couple of default ways (e.g., an HTML table).
- # You can pass it data in __init__(), as a dictionary.
- def test_form(self):
- # Pass a dictionary to a Form's __init__().
- p = Person({'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9'})
- self.assertTrue(p.is_bound)
- self.assertEqual(p.errors, {})
- self.assertTrue(p.is_valid())
- self.assertEqual(p.errors.as_ul(), u'')
- self.assertEqual(p.errors.as_text(), u'')
- self.assertEqual(p.cleaned_data["first_name"], u'John')
- self.assertEqual(p.cleaned_data["last_name"], u'Lennon')
- self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
- self.assertEqual(str(p['first_name']), '<input type="text" name="first_name" value="John" id="id_first_name" />')
- self.assertEqual(str(p['last_name']), '<input type="text" name="last_name" value="Lennon" id="id_last_name" />')
- self.assertEqual(str(p['birthday']), '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" />')
- try:
- p['nonexistentfield']
- self.fail('Attempts to access non-existent fields should fail.')
- except KeyError:
- pass
- form_output = []
- for boundfield in p:
- form_output.append(str(boundfield))
- self.assertEqual('\n'.join(form_output), """<input type="text" name="first_name" value="John" id="id_first_name" />
- <input type="text" name="last_name" value="Lennon" id="id_last_name" />
- <input type="text" name="birthday" value="1940-10-9" id="id_birthday" />""")
- form_output = []
- for boundfield in p:
- form_output.append([boundfield.label, boundfield.data])
- self.assertEqual(form_output, [
- ['First name', u'John'],
- ['Last name', u'Lennon'],
- ['Birthday', u'1940-10-9']
- ])
- self.assertEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>
- <tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="Lennon" id="id_last_name" /></td></tr>
- <tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>""")
- def test_empty_dict(self):
- # Empty dictionaries are valid, too.
- p = Person({})
- self.assertTrue(p.is_bound)
- self.assertEqual(p.errors['first_name'], [u'This field is required.'])
- self.assertEqual(p.errors['last_name'], [u'This field is required.'])
- self.assertEqual(p.errors['birthday'], [u'This field is required.'])
- self.assertFalse(p.is_valid())
- try:
- p.cleaned_data
- self.fail('Attempts to access cleaned_data when validation fails should fail.')
- except AttributeError:
- pass
- self.assertEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" id="id_first_name" /></td></tr>
- <tr><th><label for="id_last_name">Last name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="last_name" id="id_last_name" /></td></tr>
- <tr><th><label for="id_birthday">Birthday:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
- self.assertEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" id="id_first_name" /></td></tr>
- <tr><th><label for="id_last_name">Last name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="last_name" id="id_last_name" /></td></tr>
- <tr><th><label for="id_birthday">Birthday:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
- self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li>
- <li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
- <li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li>""")
- self.assertEqual(p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul>
- <p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p>
- <ul class="errorlist"><li>This field is required.</li></ul>
- <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
- <ul class="errorlist"><li>This field is required.</li></ul>
- <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>""")
- def test_unbound_form(self):
- # If you don't pass any values to the Form's __init__(), or if you pass None,
- # the Form will be considered unbound and won't do any validation. Form.errors
- # will be an empty dictionary *but* Form.is_valid() will return False.
- p = Person()
- self.assertFalse(p.is_bound)
- self.assertEqual(p.errors, {})
- self.assertFalse(p.is_valid())
- try:
- p.cleaned_data
- self.fail('Attempts to access cleaned_data when validation fails should fail.')
- except AttributeError:
- pass
- self.assertEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr>
- <tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
- <tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
- self.assertEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr>
- <tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
- <tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
- self.assertEqual(p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li>
- <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
- <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li>""")
- self.assertEqual(p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p>
- <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
- <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>""")
- def test_unicode_values(self):
- # Unicode values are handled properly.
- p = Person({'first_name': u'John', 'last_name': u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'})
- self.assertEqual(p.as_table(), u'<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>\n<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></td></tr>\n<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>')
- self.assertEqual(p.as_ul(), u'<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></li>\n<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></li>\n<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></li>')
- self.assertEqual(p.as_p(), u'<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></p>\n<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></p>\n<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></p>')
- p = Person({'last_name': u'Lennon'})
- self.assertEqual(p.errors['first_name'], [u'This field is required.'])
- self.assertEqual(p.errors['birthday'], [u'This field is required.'])
- self.assertFalse(p.is_valid())
- self.assertEqual(p.errors.as_ul(), u'<ul class="errorlist"><li>first_name<ul class="errorlist"><li>This field is required.</li></ul></li><li>birthday<ul class="errorlist"><li>This field is required.</li></ul></li></ul>')
- self.assertEqual(p.errors.as_text(), """* first_name
- * This field is required.
- * birthday
- * This field is required.""")
- try:
- p.cleaned_data
- self.fail('Attempts to access cleaned_data when validation fails should fail.')
- except AttributeError:
- pass
- self.assertEqual(p['first_name'].errors, [u'This field is required.'])
- self.assertEqual(p['first_name'].errors.as_ul(), u'<ul class="errorlist"><li>This field is required.</li></ul>')
- self.assertEqual(p['first_name'].errors.as_text(), u'* This field is required.')
- p = Person()
- self.assertEqual(str(p['first_name']), '<input type="text" name="first_name" id="id_first_name" />')
- self.assertEqual(str(p['last_name']), '<input type="text" name="last_name" id="id_last_name" />')
- self.assertEqual(str(p['birthday']), '<input type="text" name="birthday" id="id_birthday" />')
- def test_cleaned_data_only_fields(self):
- # cleaned_data will always *only* contain a key for fields defined in the
- # Form, even if you pass extra data when you define the Form. In this
- # example, we pass a bunch of extra fields to the form constructor,
- # but cleaned_data contains only the form's fields.
- data = {'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9', 'extra1': 'hello', 'extra2': 'hello'}
- p = Person(data)
- self.assertTrue(p.is_valid())
- self.assertEqual(p.cleaned_data['first_name'], u'John')
- self.assertEqual(p.cleaned_data['last_name'], u'Lennon')
- self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
- def test_optional_data(self):
- # cleaned_data will include a key and value for *all* fields defined in the Form,
- # even if the Form's data didn't include a value for fields that are not
- # required. In this example, the data dictionary doesn't include a value for the
- # "nick_name" field, but cleaned_data includes it. For CharFields, it's set to the
- # empty string.
- class OptionalPersonForm(Form):
- first_name = CharField()
- last_name = CharField()
- nick_name = CharField(required=False)
- data = {'first_name': u'John', 'last_name': u'Lennon'}
- f = OptionalPersonForm(data)
- self.assertTrue(f.is_valid())
- self.assertEqual(f.cleaned_data['nick_name'], u'')
- self.assertEqual(f.cleaned_data['first_name'], u'John')
- self.assertEqual(f.cleaned_data['last_name'], u'Lennon')
- # For DateFields, it's set to None.
- class OptionalPersonForm(Form):
- first_name = CharField()
- last_name = CharField()
- birth_date = DateField(required=False)
- data = {'first_name': u'John', 'last_name': u'Lennon'}
- f = OptionalPersonForm(data)
- self.assertTrue(f.is_valid())
- self.assertEqual(f.cleaned_data['birth_date'], None)
- self.assertEqual(f.cleaned_data['first_name'], u'John')
- self.assertEqual(f.cleaned_data['last_name'], u'Lennon')
- def test_auto_id(self):
- # "auto_id" tells the Form to add an "id" attribute to each form element.
- # If it's a string that contains '%s', Django will use that as a format string
- # into which the field's name will be inserted. It will also put a <label> around
- # the human-readable labels for a field.
- p = Person(auto_id='%s_id')
- self.assertEqual(p.as_table(), """<tr><th><label for="first_name_id">First name:</label></th><td><input type="text" name="first_name" id="first_name_id" /></td></tr>
- <tr><th><label for="last_name_id">Last name:</label></th><td><input type="text" name="last_name" id="last_name_id" /></td></tr>
- <tr><th><label for="birthday_id">Birthday:</label></th><td><input type="text" name="birthday" id="birthday_id" /></td></tr>""")
- self.assertEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" /></li>
- <li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></li>
- <li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></li>""")
- self.assertEqual(p.as_p(), """<p><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" /></p>
- <p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></p>
- <p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></p>""")
- def test_auto_id_true(self):
- # If auto_id is any True value whose str() does not contain '%s', the "id"
- # attribute will be the name of the field.
- p = Person(auto_id=True)
- self.assertEqual(p.as_ul(), """<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" /></li>
- <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li>
- <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>""")
- def test_auto_id_false(self):
- # If auto_id is any False value, an "id" attribute won't be output unless it
- # was manually entered.
- p = Person(auto_id=False)
- self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
- <li>Last name: <input type="text" name="last_name" /></li>
- <li>Birthday: <input type="text" name="birthday" /></li>""")
- def test_id_on_field(self):
- # In this example, auto_id is False, but the "id" attribute for the "first_name"
- # field is given. Also note that field gets a <label>, while the others don't.
- p = PersonNew(auto_id=False)
- self.assertEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" /></li>
- <li>Last name: <input type="text" name="last_name" /></li>
- <li>Birthday: <input type="text" name="birthday" /></li>""")
- def test_auto_id_on_form_and_field(self):
- # If the "id" attribute is specified in the Form and auto_id is True, the "id"
- # attribute in the Form gets precedence.
- p = PersonNew(auto_id=True)
- self.assertEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" /></li>
- <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li>
- <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>""")
- def test_various_boolean_values(self):
- class SignupForm(Form):
- email = EmailField()
- get_spam = BooleanField()
- f = SignupForm(auto_id=False)
- self.assertEqual(str(f['email']), '<input type="text" name="email" />')
- self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
- f = SignupForm({'email': 'test@example.com', 'get_spam': True}, auto_id=False)
- self.assertEqual(str(f['email']), '<input type="text" name="email" value="test@example.com" />')
- self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />')
- # 'True' or 'true' should be rendered without a value attribute
- f = SignupForm({'email': 'test@example.com', 'get_spam': 'True'}, auto_id=False)
- self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />')
- f = SignupForm({'email': 'test@example.com', 'get_spam': 'true'}, auto_id=False)
- self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />')
- # A value of 'False' or 'false' should be rendered unchecked
- f = SignupForm({'email': 'test@example.com', 'get_spam': 'False'}, auto_id=False)
- self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
- f = SignupForm({'email': 'test@example.com', 'get_spam': 'false'}, auto_id=False)
- self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
- def test_widget_output(self):
- # Any Field can have a Widget class passed to its constructor:
- class ContactForm(Form):
- subject = CharField()
- message = CharField(widget=Textarea)
- f = ContactForm(auto_id=False)
- self.assertEqual(str(f['subject']), '<input type="text" name="subject" />')
- self.assertEqual(str(f['message']), '<textarea rows="10" cols="40" name="message"></textarea>')
- # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output
- # widget type:
- self.assertEqual(f['subject'].as_textarea(), u'<textarea rows="10" cols="40" name="subject"></textarea>')
- self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" />')
- self.assertEqual(f['message'].as_hidden(), u'<input type="hidden" name="message" />')
- # The 'widget' parameter to a Field can also be an instance:
- class ContactForm(Form):
- subject = CharField()
- message = CharField(widget=Textarea(attrs={'rows': 80, 'cols': 20}))
- f = ContactForm(auto_id=False)
- self.assertEqual(str(f['message']), '<textarea rows="80" cols="20" name="message"></textarea>')
- # Instance-level attrs are *not* carried over to as_textarea(), as_text() and
- # as_hidden():
- self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" />')
- f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False)
- self.assertEqual(f['subject'].as_textarea(), u'<textarea rows="10" cols="40" name="subject">Hello</textarea>')
- self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" value="I love you." />')
- self.assertEqual(f['message'].as_hidden(), u'<input type="hidden" name="message" value="I love you." />')
- def test_forms_with_choices(self):
- # For a form with a <select>, use ChoiceField:
- class FrameworkForm(Form):
- name = CharField()
- language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')])
- f = FrameworkForm(auto_id=False)
- self.assertEqual(str(f['language']), """<select name="language">
- <option value="P">Python</option>
- <option value="J">Java</option>
- </select>""")
- f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
- self.assertEqual(str(f['language']), """<select name="language">
- <option value="P" selected="selected">Python</option>
- <option value="J">Java</option>
- </select>""")
- # A subtlety: If one of the choices' value is the empty string and the form is
- # unbound, then the <option> for the empty-string choice will get selected="selected".
- class FrameworkForm(Form):
- name = CharField()
- language = ChoiceField(choices=[('', '------'), ('P', 'Python'), ('J', 'Java')])
- f = FrameworkForm(auto_id=False)
- self.assertEqual(str(f['language']), """<select name="language">
- <option value="" selected="selected">------</option>
- <option value="P">Python</option>
- <option value="J">Java</option>
- </select>""")
- # You can specify widget attributes in the Widget constructor.
- class FrameworkForm(Form):
- name = CharField()
- language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(attrs={'class': 'foo'}))
- f = FrameworkForm(auto_id=False)
- self.assertEqual(str(f['language']), """<select class="foo" name="language">
- <option value="P">Python</option>
- <option value="J">Java</option>
- </select>""")
- f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
- self.assertEqual(str(f['language']), """<select class="foo" name="language">
- <option value="P" selected="selected">Python</option>
- <option value="J">Java</option>
- </select>""")
- # When passing a custom widget instance to ChoiceField, note that setting
- # 'choices' on the widget is meaningless. The widget will use the choices
- # defined on the Field, not the ones defined on the Widget.
- class FrameworkForm(Form):
- name = CharField()
- language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'}))
- f = FrameworkForm(auto_id=False)
- self.assertEqual(str(f['language']), """<select class="foo" name="language">
- <option value="P">Python</option>
- <option value="J">Java</option>
- </select>""")
- f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
- self.assertEqual(str(f['language']), """<select class="foo" name="language">
- <option value="P" selected="selected">Python</option>
- <option value="J">Java</option>
- </select>""")
- # You can set a ChoiceField's choices after the fact.
- class FrameworkForm(Form):
- name = CharField()
- language = ChoiceField()
- f = FrameworkForm(auto_id=False)
- self.assertEqual(str(f['language']), """<select name="language">
- </select>""")
- f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')]
- self.assertEqual(str(f['language']), """<select name="language">
- <option value="P">Python</option>
- <option value="J">Java</option>
- </select>""")
- def test_forms_with_radio(self):
- # Add widget=RadioSelect to use that widget with a ChoiceField.
- class FrameworkForm(Form):
- name = CharField()
- language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=RadioSelect)
- f = FrameworkForm(auto_id=False)
- self.assertEqual(str(f['language']), """<ul>
- <li><label><input type="radio" name="language" value="P" /> Python</label></li>
- <li><label><input type="radio" name="language" value="J" /> Java</label></li>
- </ul>""")
- self.assertEqual(f.as_table(), """<tr><th>Name:</th><td><input type="text" name="name" /></td></tr>
- <tr><th>Language:</th><td><ul>
- <li><label><input type="radio" name="language" value="P" /> Python</label></li>
- <li><label><input type="radio" name="language" value="J" /> Java</label></li>
- </ul></td></tr>""")
- self.assertEqual(f.as_ul(), """<li>Name: <input type="text" name="name" /></li>
- <li>Language: <ul>
- <li><label><input type="radio" name="language" value="P" /> Python</label></li>
- <li><label><input type="radio" name="language" value="J" /> Java</label></li>
- </ul></li>""")
- # Regarding auto_id and <label>, RadioSelect is a special case. Each radio button
- # gets a distinct ID, formed by appending an underscore plus the button's
- # zero-based index.
- f = FrameworkForm(auto_id='id_%s')
- self.assertEqual(str(f['language']), """<ul>
- <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
- <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
- </ul>""")
- # When RadioSelect is used with auto_id, and the whole form is printed using
- # either as_table() or as_ul(), the label for the RadioSelect will point to the
- # ID of the *first* radio button.
- self.assertEqual(f.as_table(), """<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" id="id_name" /></td></tr>
- <tr><th><label for="id_language_0">Language:</label></th><td><ul>
- <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
- <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
- </ul></td></tr>""")
- self.assertEqual(f.as_ul(), """<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></li>
- <li><label for="id_language_0">Language:</label> <ul>
- <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
- <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
- </ul></li>""")
- self.assertEqual(f.as_p(), """<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p>
- <p><label for="id_language_0">Language:</label> <ul>
- <li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
- <li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
- </ul></p>""")
- def test_forms_wit_hmultiple_choice(self):
- # MultipleChoiceField is a special case, as its data is required to be a list:
- class SongForm(Form):
- name = CharField()
- composers = MultipleChoiceField()
- f = SongForm(auto_id=False)
- self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers">
- </select>""")
- class SongForm(Form):
- name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')])
- f = SongForm(auto_id=False)
- self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers">
- <option value="J">John Lennon</option>
- <option value="P">Paul McCartney</option>
- </select>""")
- f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
- self.assertEqual(str(f['name']), '<input type="text" name="name" value="Yesterday" />')
- self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers">
- <option value="J">John Lennon</option>
- <option value="P" selected="selected">Paul McCartney</option>
- </select>""")
- def test_hidden_data(self):
- class SongForm(Form):
- name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')])
- # MultipleChoiceField rendered as_hidden() is a special case. Because it can
- # have multiple values, its as_hidden() renders multiple <input type="hidden">
- # tags.
- f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
- self.assertEqual(f['composers'].as_hidden(), '<input type="hidden" name="composers" value="P" />')
- f = SongForm({'name': 'From Me To You', 'composers': ['P', 'J']}, auto_id=False)
- self.assertEqual(f['composers'].as_hidden(), """<input type="hidden" name="composers" value="P" />
- <input type="hidden" name="composers" value="J" />""")
- # DateTimeField rendered as_hidden() is special too
- class MessageForm(Form):
- when = SplitDateTimeField()
- f = MessageForm({'when_0': '1992-01-01', 'when_1': '01:01'})
- self.assertTrue(f.is_valid())
- self.assertEqual(str(f['when']), '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" /><input type="text" name="when_1" value="01:01" id="id_when_1" />')
- self.assertEqual(f['when'].as_hidden(), '<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0" /><input type="hidden" name="when_1" value="01:01" id="id_when_1" />')
- def test_mulitple_choice_checkbox(self):
- # MultipleChoiceField can also be used with the CheckboxSelectMultiple widget.
- class SongForm(Form):
- name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
- f = SongForm(auto_id=False)
- self.assertEqual(str(f['composers']), """<ul>
- <li><label><input type="checkbox" name="composers" value="J" /> John Lennon</label></li>
- <li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
- </ul>""")
- f = SongForm({'composers': ['J']}, auto_id=False)
- self.assertEqual(str(f['composers']), """<ul>
- <li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li>
- <li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
- </ul>""")
- f = SongForm({'composers': ['J', 'P']}, auto_id=False)
- self.assertEqual(str(f['composers']), """<ul>
- <li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li>
- <li><label><input checked="checked" type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
- </ul>""")
- def test_checkbox_auto_id(self):
- # Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox
- # gets a distinct ID, formed by appending an underscore plus the checkbox's
- # zero-based index.
- class SongForm(Form):
- name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
- f = SongForm(auto_id='%s_id')
- self.assertEqual(str(f['composers']), """<ul>
- <li><label for="composers_id_0"><input type="checkbox" name="composers" value="J" id="composers_id_0" /> John Lennon</label></li>
- <li><label for="composers_id_1"><input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li>
- </ul>""")
- def test_multiple_choice_list_data(self):
- # Data for a MultipleChoiceField should be a list. QueryDict, MultiValueDict and
- # MergeDict (when created as a merge of MultiValueDicts) conveniently work with
- # this.
- class SongForm(Form):
- name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
- data = {'name': 'Yesterday', 'composers': ['J', 'P']}
- f = SongForm(data)
- self.assertEqual(f.errors, {})
- data = QueryDict('name=Yesterday&composers=J&composers=P')
- f = SongForm(data)
- self.assertEqual(f.errors, {})
- data = MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P']))
- f = SongForm(data)
- self.assertEqual(f.errors, {})
- data = MergeDict(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])))
- f = SongForm(data)
- self.assertEqual(f.errors, {})
- def test_multiple_hidden(self):
- class SongForm(Form):
- name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
- # The MultipleHiddenInput widget renders multiple values as hidden fields.
- class SongFormHidden(Form):
- name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=MultipleHiddenInput)
- f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False)
- self.assertEqual(f.as_ul(), """<li>Name: <input type="text" name="name" value="Yesterday" /><input type="hidden" name="composers" value="J" />
- <input type="hidden" name="composers" value="P" /></li>""")
- # When using CheckboxSelectMultiple, the framework expects a list of input and
- # returns a list of input.
- f = SongForm({'name': 'Yesterday'}, auto_id=False)
- self.assertEqual(f.errors['composers'], [u'This field is required.'])
- f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False)
- self.assertEqual(f.errors, {})
- self.assertEqual(f.cleaned_data['composers'], [u'J'])
- self.assertEqual(f.cleaned_data['name'], u'Yesterday')
- f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False)
- self.assertEqual(f.errors, {})
- self.assertEqual(f.cleaned_data['composers'], [u'J', u'P'])
- self.assertEqual(f.cleaned_data['name'], u'Yesterday')
- def test_escaping(self):
- # Validation errors are HTML-escaped when output as HTML.
- class EscapingForm(Form):
- special_name = CharField(label="<em>Special</em> Field")
- special_safe_name = CharField(label=mark_safe("<em>Special</em> Field"))
- def clean_special_name(self):
- raise ValidationError("Something's wrong with '%s'" % self.cleaned_data['special_name'])
- def clean_special_safe_name(self):
- raise ValidationError(mark_safe("'<b>%s</b>' is a safe string" % self.cleaned_data['special_safe_name']))
- f = EscapingForm({'special_name': "Nothing to escape", 'special_safe_name': "Nothing to escape"}, auto_id=False)
- self.assertEqual(f.as_table(), """<tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>Something's wrong with 'Nothing to escape'</li></ul><input type="text" name="special_name" value="Nothing to escape" /></td></tr>
- <tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>'<b>Nothing to escape</b>' is a safe string</li></ul><input type="text" name="special_safe_name" value="Nothing to escape" /></td></tr>""")
- f = EscapingForm({
- 'special_name': "Should escape < & > and <script>alert('xss')</script>",
- 'special_safe_name': "<i>Do not escape</i>"
- }, auto_id=False)
- self.assertEqual(f.as_table(), """<tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>Something's wrong with 'Should escape < & > and <script>alert('xss')</script>'</li></ul><input type="text" name="special_name" value="Should escape < & > and <script>alert('xss')</script>" /></td></tr>
- <tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>'<b><i>Do not escape</i></b>' is a safe string</li></ul><input type="text" name="special_safe_name" value="<i>Do not escape</i>" /></td></tr>""")
- def test_validating_multiple_fields(self):
- # There are a couple of ways to do multiple-field validation. If you want the
- # validation message to be associated with a particular field, implement the
- # clean_XXX() method on the Form, where XXX is the field name. As in
- # Field.clean(), the clean_XXX() method should return the cleaned value. In the
- # clean_XXX() method, you have access to self.cleaned_data, which is a dictionary
- # of all the data that has been cleaned *so far*, in order by the fields,
- # including the current field (e.g., the field XXX if you're in clean_XXX()).
- class UserRegistration(Form):
- username = CharField(max_length=10)
- password1 = CharField(widget=PasswordInput)
- password2 = CharField(widget=PasswordInput)
- def clean_password2(self):
- if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
- raise ValidationError(u'Please make sure your passwords match.')
- return self.cleaned_data['password2']
- f = UserRegistration(auto_id=False)
- self.assertEqual(f.errors, {})
- f = UserRegistration({}, auto_id=False)
- self.assertEqual(f.errors['username'], [u'This field is required.'])
- self.assertEqual(f.errors['password1'], [u'This field is required.'])
- self.assertEqual(f.errors['password2'], [u'This field is required.'])
- f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
- self.assertEqual(f.errors['password2'], [u'Please make sure your passwords match.'])
- f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
- self.assertEqual(f.errors, {})
- self.assertEqual(f.cleaned_data['username'], u'adrian')
- self.assertEqual(f.cleaned_data['password1'], u'foo')
- self.assertEqual(f.cleaned_data['password2'], u'foo')
- # Another way of doing multiple-field validation is by implementing the
- # Form's clean() method. If you do this, any ValidationError raised by that
- # method will not be associated with a particular field; it will have a
- # special-case association with the field named '__all__'.
- # Note that in Form.clean(), you have access to self.cleaned_data, a dictionary of
- # all the fields/values that have *not* raised a ValidationError. Also note
- # Form.clean() is required to return a dictionary of all clean data.
- class UserRegistration(Form):
- username = CharField(max_length=10)
- password1 = CharField(widget=PasswordInput)
- password2 = CharField(widget=PasswordInput)
- def clean(self):
- if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
- raise ValidationError(u'Please make sure your passwords match.')
- return self.cleaned_data
- f = UserRegistration(auto_id=False)
- self.assertEqual(f.errors, {})
- f = UserRegistration({}, auto_id=False)
- self.assertEqual(f.as_table(), """<tr><th>Username:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="username" maxlength="10" /></td></tr>
- <tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password1" /></td></tr>
- <tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password2" /></td></tr>""")
- self.assertEqual(f.errors['username'], [u'This field is required.'])
- self.assertEqual(f.errors['password1'], [u'This field is required.'])
- self.assertEqual(f.errors['password2'], [u'This field is required.'])
- f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
- self.assertEqual(f.errors['__all__'], [u'Please make sure your passwords match.'])
- self.assertEqual(f.as_table(), """<tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr>
- <tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" /></td></tr>
- <tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr>
- <tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>""")
- self.assertEqual(f.as_ul(), """<li><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></li>
- <li>Username: <input type="text" name="username" value="adrian" maxlength="10" /></li>
- <li>Password1: <input type="password" name="password1" /></li>
- <li>Password2: <input type="password" name="password2" /></li>""")
- f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
- self.assertEqual(f.errors, {})
- self.assertEqual(f.cleaned_data['username'], u'adrian')
- self.assertEqual(f.cleaned_data['password1'], u'foo')
- self.assertEqual(f.cleaned_data['password2'], u'foo')
- def test_dynamic_construction(self):
- # It's possible to construct a Form dynamically by adding to the self.fields
- # dictionary in __init__(). Don't forget to call Form.__init__() within the
- # subclass' __init__().
- class Person(Form):
- first_name = CharField()
- last_name = CharField()
- def __init__(self, *args, **kwargs):
- super(Person, self).__init__(*args, **kwargs)
- self.fields['birthday'] = DateField()
- p = Person(auto_id=False)
- self.assertEqual(p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr>
- <tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr>
- <tr><th>Birthday:</th><td><input type="text" name="birthday" /></td></tr>""")
- # Instances of a dynamic Form do not persist fields from one Form instance to
- # the next.
- class MyForm(Form):
- def __init__(self, data=None, auto_id=False, field_list=[]):
- Form.__init__(self, data, auto_id=auto_id)
- for field in field_list:
- self.fields[field[0]] = field[1]
- field_list = [('field1', CharField()), ('field2', CharField())]
- my_form = MyForm(field_list=field_list)
- self.assertEqual(my_form.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
- <tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>""")
- field_list = [('field3', CharField()), ('field4', CharField())]
- my_form = MyForm(field_list=field_list)
- self.assertEqual(my_form.as_table(), """<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
- <tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>""")
- class MyForm(Form):
- default_field_1 = CharField()
- default_field_2 = CharField()
- def __init__(self, data=None, auto_id=False, field_list=[]):
- Form.__init__(self, data, auto_id=auto_id)
- for field in field_list:
- self.fields[field[0]] = field[1]
- field_list = [('field1', CharField()), ('field2', CharField())]
- my_form = MyForm(field_list=field_list)
- self.assertEqual(my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr>
- <tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr>
- <tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
- <tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>""")
- field_list = [('field3', CharField()), ('field4', CharField())]
- my_form = MyForm(field_list=field_list)
- self.assertEqual(my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr>
- <tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr>
- <tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
- <tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>""")
- # Similarly, changes to field attributes do not persist from one Form instance
- # to the next.
- class Person(Form):
- first_name = CharField(required=False)
- last_name = CharField(required=False)
- def __init__(self, names_required=False, *args, **kwargs):
- super(Person, self).__init__(*args, **kwargs)
- if names_required:
- self.fields['first_name'].required = True
- self.fields['first_name'].widget.attrs['class'] = 'required'
- self.fields['last_name'].required = True
- self.fields['last_name'].widget.attrs['class'] = 'required'
- f = Person(names_required=False)
- self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
- self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
- f = Person(names_required=True)
- self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (True, True))
- self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({'class': 'required'}, {'class': 'required'}))
- f = Person(names_required=False)
- self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
- self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
- class Person(Form):
- first_name = CharField(max_length=30)
- last_name = CharField(max_length=30)
- def __init__(self, name_max_length=None, *args, **kwargs):
- super(Person, self).__init__(*args, **kwargs)
- if name_max_length:
- self.fields['first_name'].max_length = name_max_length
- self.fields['last_name'].max_length = name_max_length
- f = Person(name_max_length=None)
- self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
- f = Person(name_max_length=20)
- self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (20, 20))
- f = Person(name_max_length=None)
- self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
- def test_hidden_widget(self):
- # HiddenInput widgets are displayed differently in the as_table(), as_ul())
- # and as_p() output of a Form -- their verbose names are not displayed, and a
- # separate row is not displayed. They're displayed in the last row of the
- # form, directly after that row's form element.
- class Person(Form):
- first_name = CharField()
- last_name = CharField()
- hidden_text = CharField(widget=HiddenInput)
- birthday = DateField()
- p = Person(auto_id=False)
- self.assertEqual(p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr>
- <tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr>
- <tr><th>Birthday:</th><td><input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></td></tr>""")
- self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
- <li>Last name: <input type="text" name="last_name" /></li>
- <li>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></li>""")
- self.assertEqual(p.as_p(), """<p>First name: <input type="text" name="first_name" /></p>
- <p>Last name: <input type="text" name="last_name" /></p>
- <p>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></p>""")
- # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
- p = Person(auto_id='id_%s')
- self.assertEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr>
- <tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
- <tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></td></tr>""")
- self.assertEqual(p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li>
- <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
- <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></li>""")
- self.assertEqual(p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p>
- <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
- <p><label for="id_b…
Large files files are truncated, but you can click here to view the full file