PageRenderTime 124ms CodeModel.GetById 3ms app.highlight 102ms RepoModel.GetById 1ms app.codeStats 1ms

/tests/regressiontests/forms/tests/forms.py

https://code.google.com/p/mango-py/
Python | 1724 lines | 1683 code | 16 blank | 25 comment | 10 complexity | 17beefea3cf04a0dedfb41b9e743e8a2 MD5 | raw file
   1# -*- coding: utf-8 -*-
   2import datetime
   3from decimal import Decimal
   4import re
   5import time
   6from django.core.files.uploadedfile import SimpleUploadedFile
   7from django.forms import *
   8from django.http import QueryDict
   9from django.template import Template, Context
  10from django.utils.datastructures import MultiValueDict, MergeDict
  11from django.utils.safestring import mark_safe
  12from django.utils.unittest import TestCase
  13
  14
  15class Person(Form):
  16    first_name = CharField()
  17    last_name = CharField()
  18    birthday = DateField()
  19
  20
  21class PersonNew(Form):
  22    first_name = CharField(widget=TextInput(attrs={'id': 'first_name_id'}))
  23    last_name = CharField()
  24    birthday = DateField()
  25
  26
  27class FormsTestCase(TestCase):
  28    # A Form is a collection of Fields. It knows how to validate a set of data and it
  29    # knows how to render itself in a couple of default ways (e.g., an HTML table).
  30    # You can pass it data in __init__(), as a dictionary.
  31
  32    def test_form(self):
  33        # Pass a dictionary to a Form's __init__().
  34        p = Person({'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9'})
  35
  36        self.assertTrue(p.is_bound)
  37        self.assertEqual(p.errors, {})
  38        self.assertTrue(p.is_valid())
  39        self.assertEqual(p.errors.as_ul(), u'')
  40        self.assertEqual(p.errors.as_text(), u'')
  41        self.assertEqual(p.cleaned_data["first_name"], u'John')
  42        self.assertEqual(p.cleaned_data["last_name"], u'Lennon')
  43        self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
  44        self.assertEqual(str(p['first_name']), '<input type="text" name="first_name" value="John" id="id_first_name" />')
  45        self.assertEqual(str(p['last_name']), '<input type="text" name="last_name" value="Lennon" id="id_last_name" />')
  46        self.assertEqual(str(p['birthday']), '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" />')
  47        try:
  48            p['nonexistentfield']
  49            self.fail('Attempts to access non-existent fields should fail.')
  50        except KeyError:
  51            pass
  52
  53        form_output = []
  54
  55        for boundfield in p:
  56            form_output.append(str(boundfield))
  57
  58        self.assertEqual('\n'.join(form_output), """<input type="text" name="first_name" value="John" id="id_first_name" />
  59<input type="text" name="last_name" value="Lennon" id="id_last_name" />
  60<input type="text" name="birthday" value="1940-10-9" id="id_birthday" />""")
  61
  62        form_output = []
  63
  64        for boundfield in p:
  65            form_output.append([boundfield.label, boundfield.data])
  66
  67        self.assertEqual(form_output, [
  68            ['First name', u'John'],
  69            ['Last name', u'Lennon'],
  70            ['Birthday', u'1940-10-9']
  71        ])
  72        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>
  73<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>
  74<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>""")
  75
  76    def test_empty_dict(self):
  77        # Empty dictionaries are valid, too.
  78        p = Person({})
  79        self.assertTrue(p.is_bound)
  80        self.assertEqual(p.errors['first_name'], [u'This field is required.'])
  81        self.assertEqual(p.errors['last_name'], [u'This field is required.'])
  82        self.assertEqual(p.errors['birthday'], [u'This field is required.'])
  83        self.assertFalse(p.is_valid())
  84        try:
  85            p.cleaned_data
  86            self.fail('Attempts to access cleaned_data when validation fails should fail.')
  87        except AttributeError:
  88            pass
  89        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>
  90<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>
  91<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>""")
  92        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>
  93<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>
  94<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>""")
  95        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>
  96<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>
  97<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>""")
  98        self.assertEqual(p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul>
  99<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p>
 100<ul class="errorlist"><li>This field is required.</li></ul>
 101<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
 102<ul class="errorlist"><li>This field is required.</li></ul>
 103<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>""")
 104
 105    def test_unbound_form(self):
 106        # If you don't pass any values to the Form's __init__(), or if you pass None,
 107        # the Form will be considered unbound and won't do any validation. Form.errors
 108        # will be an empty dictionary *but* Form.is_valid() will return False.
 109        p = Person()
 110        self.assertFalse(p.is_bound)
 111        self.assertEqual(p.errors, {})
 112        self.assertFalse(p.is_valid())
 113        try:
 114            p.cleaned_data
 115            self.fail('Attempts to access cleaned_data when validation fails should fail.')
 116        except AttributeError:
 117            pass
 118        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>
 119<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
 120<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
 121        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>
 122<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
 123<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>""")
 124        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>
 125<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
 126<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li>""")
 127        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>
 128<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
 129<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>""")
 130
 131    def test_unicode_values(self):
 132        # Unicode values are handled properly.
 133        p = Person({'first_name': u'John', 'last_name': u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'})
 134        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>')
 135        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>')
 136        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>')
 137
 138        p = Person({'last_name': u'Lennon'})
 139        self.assertEqual(p.errors['first_name'], [u'This field is required.'])
 140        self.assertEqual(p.errors['birthday'], [u'This field is required.'])
 141        self.assertFalse(p.is_valid())
 142        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>')
 143        self.assertEqual(p.errors.as_text(), """* first_name
 144  * This field is required.
 145* birthday
 146  * This field is required.""")
 147        try:
 148            p.cleaned_data
 149            self.fail('Attempts to access cleaned_data when validation fails should fail.')
 150        except AttributeError:
 151            pass
 152        self.assertEqual(p['first_name'].errors, [u'This field is required.'])
 153        self.assertEqual(p['first_name'].errors.as_ul(), u'<ul class="errorlist"><li>This field is required.</li></ul>')
 154        self.assertEqual(p['first_name'].errors.as_text(), u'* This field is required.')
 155
 156        p = Person()
 157        self.assertEqual(str(p['first_name']), '<input type="text" name="first_name" id="id_first_name" />')
 158        self.assertEqual(str(p['last_name']), '<input type="text" name="last_name" id="id_last_name" />')
 159        self.assertEqual(str(p['birthday']), '<input type="text" name="birthday" id="id_birthday" />')
 160
 161    def test_cleaned_data_only_fields(self):
 162        # cleaned_data will always *only* contain a key for fields defined in the
 163        # Form, even if you pass extra data when you define the Form. In this
 164        # example, we pass a bunch of extra fields to the form constructor,
 165        # but cleaned_data contains only the form's fields.
 166        data = {'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9', 'extra1': 'hello', 'extra2': 'hello'}
 167        p = Person(data)
 168        self.assertTrue(p.is_valid())
 169        self.assertEqual(p.cleaned_data['first_name'], u'John')
 170        self.assertEqual(p.cleaned_data['last_name'], u'Lennon')
 171        self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
 172
 173    def test_optional_data(self):
 174        # cleaned_data will include a key and value for *all* fields defined in the Form,
 175        # even if the Form's data didn't include a value for fields that are not
 176        # required. In this example, the data dictionary doesn't include a value for the
 177        # "nick_name" field, but cleaned_data includes it. For CharFields, it's set to the
 178        # empty string.
 179        class OptionalPersonForm(Form):
 180            first_name = CharField()
 181            last_name = CharField()
 182            nick_name = CharField(required=False)
 183
 184        data = {'first_name': u'John', 'last_name': u'Lennon'}
 185        f = OptionalPersonForm(data)
 186        self.assertTrue(f.is_valid())
 187        self.assertEqual(f.cleaned_data['nick_name'], u'')
 188        self.assertEqual(f.cleaned_data['first_name'], u'John')
 189        self.assertEqual(f.cleaned_data['last_name'], u'Lennon')
 190
 191        # For DateFields, it's set to None.
 192        class OptionalPersonForm(Form):
 193            first_name = CharField()
 194            last_name = CharField()
 195            birth_date = DateField(required=False)
 196
 197        data = {'first_name': u'John', 'last_name': u'Lennon'}
 198        f = OptionalPersonForm(data)
 199        self.assertTrue(f.is_valid())
 200        self.assertEqual(f.cleaned_data['birth_date'], None)
 201        self.assertEqual(f.cleaned_data['first_name'], u'John')
 202        self.assertEqual(f.cleaned_data['last_name'], u'Lennon')
 203
 204    def test_auto_id(self):
 205        # "auto_id" tells the Form to add an "id" attribute to each form element.
 206        # If it's a string that contains '%s', Django will use that as a format string
 207        # into which the field's name will be inserted. It will also put a <label> around
 208        # the human-readable labels for a field.
 209        p = Person(auto_id='%s_id')
 210        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>
 211<tr><th><label for="last_name_id">Last name:</label></th><td><input type="text" name="last_name" id="last_name_id" /></td></tr>
 212<tr><th><label for="birthday_id">Birthday:</label></th><td><input type="text" name="birthday" id="birthday_id" /></td></tr>""")
 213        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>
 214<li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></li>
 215<li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></li>""")
 216        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>
 217<p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></p>
 218<p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></p>""")
 219
 220    def test_auto_id_true(self):
 221        # If auto_id is any True value whose str() does not contain '%s', the "id"
 222        # attribute will be the name of the field.
 223        p = Person(auto_id=True)
 224        self.assertEqual(p.as_ul(), """<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" /></li>
 225<li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li>
 226<li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>""")
 227
 228    def test_auto_id_false(self):
 229        # If auto_id is any False value, an "id" attribute won't be output unless it
 230        # was manually entered.
 231        p = Person(auto_id=False)
 232        self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
 233<li>Last name: <input type="text" name="last_name" /></li>
 234<li>Birthday: <input type="text" name="birthday" /></li>""")
 235
 236    def test_id_on_field(self):
 237        # In this example, auto_id is False, but the "id" attribute for the "first_name"
 238        # field is given. Also note that field gets a <label>, while the others don't.
 239        p = PersonNew(auto_id=False)
 240        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>
 241<li>Last name: <input type="text" name="last_name" /></li>
 242<li>Birthday: <input type="text" name="birthday" /></li>""")
 243
 244    def test_auto_id_on_form_and_field(self):
 245        # If the "id" attribute is specified in the Form and auto_id is True, the "id"
 246        # attribute in the Form gets precedence.
 247        p = PersonNew(auto_id=True)
 248        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>
 249<li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li>
 250<li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>""")
 251
 252    def test_various_boolean_values(self):
 253        class SignupForm(Form):
 254            email = EmailField()
 255            get_spam = BooleanField()
 256
 257        f = SignupForm(auto_id=False)
 258        self.assertEqual(str(f['email']), '<input type="text" name="email" />')
 259        self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
 260
 261        f = SignupForm({'email': 'test@example.com', 'get_spam': True}, auto_id=False)
 262        self.assertEqual(str(f['email']), '<input type="text" name="email" value="test@example.com" />')
 263        self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />')
 264
 265        # 'True' or 'true' should be rendered without a value attribute
 266        f = SignupForm({'email': 'test@example.com', 'get_spam': 'True'}, auto_id=False)
 267        self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />')
 268
 269        f = SignupForm({'email': 'test@example.com', 'get_spam': 'true'}, auto_id=False)
 270        self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />')
 271
 272        # A value of 'False' or 'false' should be rendered unchecked
 273        f = SignupForm({'email': 'test@example.com', 'get_spam': 'False'}, auto_id=False)
 274        self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
 275
 276        f = SignupForm({'email': 'test@example.com', 'get_spam': 'false'}, auto_id=False)
 277        self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
 278
 279    def test_widget_output(self):
 280        # Any Field can have a Widget class passed to its constructor:
 281        class ContactForm(Form):
 282            subject = CharField()
 283            message = CharField(widget=Textarea)
 284
 285        f = ContactForm(auto_id=False)
 286        self.assertEqual(str(f['subject']), '<input type="text" name="subject" />')
 287        self.assertEqual(str(f['message']), '<textarea rows="10" cols="40" name="message"></textarea>')
 288
 289        # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output
 290        # widget type:
 291        self.assertEqual(f['subject'].as_textarea(), u'<textarea rows="10" cols="40" name="subject"></textarea>')
 292        self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" />')
 293        self.assertEqual(f['message'].as_hidden(), u'<input type="hidden" name="message" />')
 294
 295        # The 'widget' parameter to a Field can also be an instance:
 296        class ContactForm(Form):
 297            subject = CharField()
 298            message = CharField(widget=Textarea(attrs={'rows': 80, 'cols': 20}))
 299
 300        f = ContactForm(auto_id=False)
 301        self.assertEqual(str(f['message']), '<textarea rows="80" cols="20" name="message"></textarea>')
 302
 303        # Instance-level attrs are *not* carried over to as_textarea(), as_text() and
 304        # as_hidden():
 305        self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" />')
 306        f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False)
 307        self.assertEqual(f['subject'].as_textarea(), u'<textarea rows="10" cols="40" name="subject">Hello</textarea>')
 308        self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" value="I love you." />')
 309        self.assertEqual(f['message'].as_hidden(), u'<input type="hidden" name="message" value="I love you." />')
 310
 311    def test_forms_with_choices(self):
 312        # For a form with a <select>, use ChoiceField:
 313        class FrameworkForm(Form):
 314            name = CharField()
 315            language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')])
 316
 317        f = FrameworkForm(auto_id=False)
 318        self.assertEqual(str(f['language']), """<select name="language">
 319<option value="P">Python</option>
 320<option value="J">Java</option>
 321</select>""")
 322        f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
 323        self.assertEqual(str(f['language']), """<select name="language">
 324<option value="P" selected="selected">Python</option>
 325<option value="J">Java</option>
 326</select>""")
 327
 328        # A subtlety: If one of the choices' value is the empty string and the form is
 329        # unbound, then the <option> for the empty-string choice will get selected="selected".
 330        class FrameworkForm(Form):
 331            name = CharField()
 332            language = ChoiceField(choices=[('', '------'), ('P', 'Python'), ('J', 'Java')])
 333
 334        f = FrameworkForm(auto_id=False)
 335        self.assertEqual(str(f['language']), """<select name="language">
 336<option value="" selected="selected">------</option>
 337<option value="P">Python</option>
 338<option value="J">Java</option>
 339</select>""")
 340
 341        # You can specify widget attributes in the Widget constructor.
 342        class FrameworkForm(Form):
 343            name = CharField()
 344            language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(attrs={'class': 'foo'}))
 345
 346        f = FrameworkForm(auto_id=False)
 347        self.assertEqual(str(f['language']), """<select class="foo" name="language">
 348<option value="P">Python</option>
 349<option value="J">Java</option>
 350</select>""")
 351        f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
 352        self.assertEqual(str(f['language']), """<select class="foo" name="language">
 353<option value="P" selected="selected">Python</option>
 354<option value="J">Java</option>
 355</select>""")
 356
 357        # When passing a custom widget instance to ChoiceField, note that setting
 358        # 'choices' on the widget is meaningless. The widget will use the choices
 359        # defined on the Field, not the ones defined on the Widget.
 360        class FrameworkForm(Form):
 361            name = CharField()
 362            language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'}))
 363
 364        f = FrameworkForm(auto_id=False)
 365        self.assertEqual(str(f['language']), """<select class="foo" name="language">
 366<option value="P">Python</option>
 367<option value="J">Java</option>
 368</select>""")
 369        f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
 370        self.assertEqual(str(f['language']), """<select class="foo" name="language">
 371<option value="P" selected="selected">Python</option>
 372<option value="J">Java</option>
 373</select>""")
 374
 375        # You can set a ChoiceField's choices after the fact.
 376        class FrameworkForm(Form):
 377            name = CharField()
 378            language = ChoiceField()
 379
 380        f = FrameworkForm(auto_id=False)
 381        self.assertEqual(str(f['language']), """<select name="language">
 382</select>""")
 383        f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')]
 384        self.assertEqual(str(f['language']), """<select name="language">
 385<option value="P">Python</option>
 386<option value="J">Java</option>
 387</select>""")
 388
 389    def test_forms_with_radio(self):
 390        # Add widget=RadioSelect to use that widget with a ChoiceField.
 391        class FrameworkForm(Form):
 392            name = CharField()
 393            language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=RadioSelect)
 394
 395        f = FrameworkForm(auto_id=False)
 396        self.assertEqual(str(f['language']), """<ul>
 397<li><label><input type="radio" name="language" value="P" /> Python</label></li>
 398<li><label><input type="radio" name="language" value="J" /> Java</label></li>
 399</ul>""")
 400        self.assertEqual(f.as_table(), """<tr><th>Name:</th><td><input type="text" name="name" /></td></tr>
 401<tr><th>Language:</th><td><ul>
 402<li><label><input type="radio" name="language" value="P" /> Python</label></li>
 403<li><label><input type="radio" name="language" value="J" /> Java</label></li>
 404</ul></td></tr>""")
 405        self.assertEqual(f.as_ul(), """<li>Name: <input type="text" name="name" /></li>
 406<li>Language: <ul>
 407<li><label><input type="radio" name="language" value="P" /> Python</label></li>
 408<li><label><input type="radio" name="language" value="J" /> Java</label></li>
 409</ul></li>""")
 410
 411        # Regarding auto_id and <label>, RadioSelect is a special case. Each radio button
 412        # gets a distinct ID, formed by appending an underscore plus the button's
 413        # zero-based index.
 414        f = FrameworkForm(auto_id='id_%s')
 415        self.assertEqual(str(f['language']), """<ul>
 416<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
 417<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
 418</ul>""")
 419
 420        # When RadioSelect is used with auto_id, and the whole form is printed using
 421        # either as_table() or as_ul(), the label for the RadioSelect will point to the
 422        # ID of the *first* radio button.
 423        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>
 424<tr><th><label for="id_language_0">Language:</label></th><td><ul>
 425<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
 426<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
 427</ul></td></tr>""")
 428        self.assertEqual(f.as_ul(), """<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></li>
 429<li><label for="id_language_0">Language:</label> <ul>
 430<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
 431<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
 432</ul></li>""")
 433        self.assertEqual(f.as_p(), """<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p>
 434<p><label for="id_language_0">Language:</label> <ul>
 435<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
 436<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
 437</ul></p>""")
 438
 439    def test_forms_wit_hmultiple_choice(self):
 440        # MultipleChoiceField is a special case, as its data is required to be a list:
 441        class SongForm(Form):
 442            name = CharField()
 443            composers = MultipleChoiceField()
 444
 445        f = SongForm(auto_id=False)
 446        self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers">
 447</select>""")
 448
 449        class SongForm(Form):
 450            name = CharField()
 451            composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')])
 452
 453        f = SongForm(auto_id=False)
 454        self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers">
 455<option value="J">John Lennon</option>
 456<option value="P">Paul McCartney</option>
 457</select>""")
 458        f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
 459        self.assertEqual(str(f['name']), '<input type="text" name="name" value="Yesterday" />')
 460        self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers">
 461<option value="J">John Lennon</option>
 462<option value="P" selected="selected">Paul McCartney</option>
 463</select>""")
 464
 465    def test_hidden_data(self):
 466        class SongForm(Form):
 467            name = CharField()
 468            composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')])
 469
 470        # MultipleChoiceField rendered as_hidden() is a special case. Because it can
 471        # have multiple values, its as_hidden() renders multiple <input type="hidden">
 472        # tags.
 473        f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
 474        self.assertEqual(f['composers'].as_hidden(), '<input type="hidden" name="composers" value="P" />')
 475        f = SongForm({'name': 'From Me To You', 'composers': ['P', 'J']}, auto_id=False)
 476        self.assertEqual(f['composers'].as_hidden(), """<input type="hidden" name="composers" value="P" />
 477<input type="hidden" name="composers" value="J" />""")
 478
 479        # DateTimeField rendered as_hidden() is special too
 480        class MessageForm(Form):
 481            when = SplitDateTimeField()
 482
 483        f = MessageForm({'when_0': '1992-01-01', 'when_1': '01:01'})
 484        self.assertTrue(f.is_valid())
 485        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" />')
 486        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" />')
 487
 488    def test_mulitple_choice_checkbox(self):
 489        # MultipleChoiceField can also be used with the CheckboxSelectMultiple widget.
 490        class SongForm(Form):
 491            name = CharField()
 492            composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
 493
 494        f = SongForm(auto_id=False)
 495        self.assertEqual(str(f['composers']), """<ul>
 496<li><label><input type="checkbox" name="composers" value="J" /> John Lennon</label></li>
 497<li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
 498</ul>""")
 499        f = SongForm({'composers': ['J']}, auto_id=False)
 500        self.assertEqual(str(f['composers']), """<ul>
 501<li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li>
 502<li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
 503</ul>""")
 504        f = SongForm({'composers': ['J', 'P']}, auto_id=False)
 505        self.assertEqual(str(f['composers']), """<ul>
 506<li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li>
 507<li><label><input checked="checked" type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
 508</ul>""")
 509
 510    def test_checkbox_auto_id(self):
 511        # Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox
 512        # gets a distinct ID, formed by appending an underscore plus the checkbox's
 513        # zero-based index.
 514        class SongForm(Form):
 515            name = CharField()
 516            composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
 517
 518        f = SongForm(auto_id='%s_id')
 519        self.assertEqual(str(f['composers']), """<ul>
 520<li><label for="composers_id_0"><input type="checkbox" name="composers" value="J" id="composers_id_0" /> John Lennon</label></li>
 521<li><label for="composers_id_1"><input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li>
 522</ul>""")
 523
 524    def test_multiple_choice_list_data(self):
 525        # Data for a MultipleChoiceField should be a list. QueryDict, MultiValueDict and
 526        # MergeDict (when created as a merge of MultiValueDicts) conveniently work with
 527        # this.
 528        class SongForm(Form):
 529            name = CharField()
 530            composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
 531
 532        data = {'name': 'Yesterday', 'composers': ['J', 'P']}
 533        f = SongForm(data)
 534        self.assertEqual(f.errors, {})
 535
 536        data = QueryDict('name=Yesterday&composers=J&composers=P')
 537        f = SongForm(data)
 538        self.assertEqual(f.errors, {})
 539
 540        data = MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P']))
 541        f = SongForm(data)
 542        self.assertEqual(f.errors, {})
 543
 544        data = MergeDict(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])))
 545        f = SongForm(data)
 546        self.assertEqual(f.errors, {})
 547
 548    def test_multiple_hidden(self):
 549        class SongForm(Form):
 550            name = CharField()
 551            composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
 552
 553        # The MultipleHiddenInput widget renders multiple values as hidden fields.
 554        class SongFormHidden(Form):
 555            name = CharField()
 556            composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=MultipleHiddenInput)
 557
 558        f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False)
 559        self.assertEqual(f.as_ul(), """<li>Name: <input type="text" name="name" value="Yesterday" /><input type="hidden" name="composers" value="J" />
 560<input type="hidden" name="composers" value="P" /></li>""")
 561
 562        # When using CheckboxSelectMultiple, the framework expects a list of input and
 563        # returns a list of input.
 564        f = SongForm({'name': 'Yesterday'}, auto_id=False)
 565        self.assertEqual(f.errors['composers'], [u'This field is required.'])
 566        f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False)
 567        self.assertEqual(f.errors, {})
 568        self.assertEqual(f.cleaned_data['composers'], [u'J'])
 569        self.assertEqual(f.cleaned_data['name'], u'Yesterday')
 570        f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False)
 571        self.assertEqual(f.errors, {})
 572        self.assertEqual(f.cleaned_data['composers'], [u'J', u'P'])
 573        self.assertEqual(f.cleaned_data['name'], u'Yesterday')
 574
 575    def test_escaping(self):
 576        # Validation errors are HTML-escaped when output as HTML.
 577        class EscapingForm(Form):
 578            special_name = CharField(label="<em>Special</em> Field")
 579            special_safe_name = CharField(label=mark_safe("<em>Special</em> Field"))
 580
 581            def clean_special_name(self):
 582                raise ValidationError("Something's wrong with '%s'" % self.cleaned_data['special_name'])
 583
 584            def clean_special_safe_name(self):
 585                raise ValidationError(mark_safe("'<b>%s</b>' is a safe string" % self.cleaned_data['special_safe_name']))
 586
 587        f = EscapingForm({'special_name': "Nothing to escape", 'special_safe_name': "Nothing to escape"}, auto_id=False)
 588        self.assertEqual(f.as_table(), """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td><ul class="errorlist"><li>Something&#39;s wrong with &#39;Nothing to escape&#39;</li></ul><input type="text" name="special_name" value="Nothing to escape" /></td></tr>
 589<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>""")
 590        f = EscapingForm({
 591            'special_name': "Should escape < & > and <script>alert('xss')</script>",
 592            'special_safe_name': "<i>Do not escape</i>"
 593        }, auto_id=False)
 594        self.assertEqual(f.as_table(), """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td><ul class="errorlist"><li>Something&#39;s wrong with &#39;Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;&#39;</li></ul><input type="text" name="special_name" value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;" /></td></tr>
 595<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="&lt;i&gt;Do not escape&lt;/i&gt;" /></td></tr>""")
 596
 597    def test_validating_multiple_fields(self):
 598        # There are a couple of ways to do multiple-field validation. If you want the
 599        # validation message to be associated with a particular field, implement the
 600        # clean_XXX() method on the Form, where XXX is the field name. As in
 601        # Field.clean(), the clean_XXX() method should return the cleaned value. In the
 602        # clean_XXX() method, you have access to self.cleaned_data, which is a dictionary
 603        # of all the data that has been cleaned *so far*, in order by the fields,
 604        # including the current field (e.g., the field XXX if you're in clean_XXX()).
 605        class UserRegistration(Form):
 606            username = CharField(max_length=10)
 607            password1 = CharField(widget=PasswordInput)
 608            password2 = CharField(widget=PasswordInput)
 609
 610            def clean_password2(self):
 611                if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
 612                    raise ValidationError(u'Please make sure your passwords match.')
 613
 614                return self.cleaned_data['password2']
 615
 616        f = UserRegistration(auto_id=False)
 617        self.assertEqual(f.errors, {})
 618        f = UserRegistration({}, auto_id=False)
 619        self.assertEqual(f.errors['username'], [u'This field is required.'])
 620        self.assertEqual(f.errors['password1'], [u'This field is required.'])
 621        self.assertEqual(f.errors['password2'], [u'This field is required.'])
 622        f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
 623        self.assertEqual(f.errors['password2'], [u'Please make sure your passwords match.'])
 624        f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
 625        self.assertEqual(f.errors, {})
 626        self.assertEqual(f.cleaned_data['username'], u'adrian')
 627        self.assertEqual(f.cleaned_data['password1'], u'foo')
 628        self.assertEqual(f.cleaned_data['password2'], u'foo')
 629
 630        # Another way of doing multiple-field validation is by implementing the
 631        # Form's clean() method. If you do this, any ValidationError raised by that
 632        # method will not be associated with a particular field; it will have a
 633        # special-case association with the field named '__all__'.
 634        # Note that in Form.clean(), you have access to self.cleaned_data, a dictionary of
 635        # all the fields/values that have *not* raised a ValidationError. Also note
 636        # Form.clean() is required to return a dictionary of all clean data.
 637        class UserRegistration(Form):
 638            username = CharField(max_length=10)
 639            password1 = CharField(widget=PasswordInput)
 640            password2 = CharField(widget=PasswordInput)
 641
 642            def clean(self):
 643                if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
 644                    raise ValidationError(u'Please make sure your passwords match.')
 645
 646                return self.cleaned_data
 647
 648        f = UserRegistration(auto_id=False)
 649        self.assertEqual(f.errors, {})
 650        f = UserRegistration({}, auto_id=False)
 651        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>
 652<tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password1" /></td></tr>
 653<tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password2" /></td></tr>""")
 654        self.assertEqual(f.errors['username'], [u'This field is required.'])
 655        self.assertEqual(f.errors['password1'], [u'This field is required.'])
 656        self.assertEqual(f.errors['password2'], [u'This field is required.'])
 657        f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
 658        self.assertEqual(f.errors['__all__'], [u'Please make sure your passwords match.'])
 659        self.assertEqual(f.as_table(), """<tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr>
 660<tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" /></td></tr>
 661<tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr>
 662<tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>""")
 663        self.assertEqual(f.as_ul(), """<li><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></li>
 664<li>Username: <input type="text" name="username" value="adrian" maxlength="10" /></li>
 665<li>Password1: <input type="password" name="password1" /></li>
 666<li>Password2: <input type="password" name="password2" /></li>""")
 667        f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
 668        self.assertEqual(f.errors, {})
 669        self.assertEqual(f.cleaned_data['username'], u'adrian')
 670        self.assertEqual(f.cleaned_data['password1'], u'foo')
 671        self.assertEqual(f.cleaned_data['password2'], u'foo')
 672
 673    def test_dynamic_construction(self):
 674        # It's possible to construct a Form dynamically by adding to the self.fields
 675        # dictionary in __init__(). Don't forget to call Form.__init__() within the
 676        # subclass' __init__().
 677        class Person(Form):
 678            first_name = CharField()
 679            last_name = CharField()
 680
 681            def __init__(self, *args, **kwargs):
 682                super(Person, self).__init__(*args, **kwargs)
 683                self.fields['birthday'] = DateField()
 684
 685        p = Person(auto_id=False)
 686        self.assertEqual(p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr>
 687<tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr>
 688<tr><th>Birthday:</th><td><input type="text" name="birthday" /></td></tr>""")
 689
 690        # Instances of a dynamic Form do not persist fields from one Form instance to
 691        # the next.
 692        class MyForm(Form):
 693            def __init__(self, data=None, auto_id=False, field_list=[]):
 694                Form.__init__(self, data, auto_id=auto_id)
 695
 696                for field in field_list:
 697                    self.fields[field[0]] = field[1]
 698
 699        field_list = [('field1', CharField()), ('field2', CharField())]
 700        my_form = MyForm(field_list=field_list)
 701        self.assertEqual(my_form.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
 702<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>""")
 703        field_list = [('field3', CharField()), ('field4', CharField())]
 704        my_form = MyForm(field_list=field_list)
 705        self.assertEqual(my_form.as_table(), """<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
 706<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>""")
 707
 708        class MyForm(Form):
 709            default_field_1 = CharField()
 710            default_field_2 = CharField()
 711
 712            def __init__(self, data=None, auto_id=False, field_list=[]):
 713                Form.__init__(self, data, auto_id=auto_id)
 714
 715                for field in field_list:
 716                    self.fields[field[0]] = field[1]
 717
 718        field_list = [('field1', CharField()), ('field2', CharField())]
 719        my_form = MyForm(field_list=field_list)
 720        self.assertEqual(my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr>
 721<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr>
 722<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
 723<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>""")
 724        field_list = [('field3', CharField()), ('field4', CharField())]
 725        my_form = MyForm(field_list=field_list)
 726        self.assertEqual(my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr>
 727<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr>
 728<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
 729<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>""")
 730
 731        # Similarly, changes to field attributes do not persist from one Form instance
 732        # to the next.
 733        class Person(Form):
 734            first_name = CharField(required=False)
 735            last_name = CharField(required=False)
 736
 737            def __init__(self, names_required=False, *args, **kwargs):
 738                super(Person, self).__init__(*args, **kwargs)
 739
 740                if names_required:
 741                    self.fields['first_name'].required = True
 742                    self.fields['first_name'].widget.attrs['class'] = 'required'
 743                    self.fields['last_name'].required = True
 744                    self.fields['last_name'].widget.attrs['class'] = 'required'
 745
 746        f = Person(names_required=False)
 747        self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
 748        self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
 749        f = Person(names_required=True)
 750        self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (True, True))
 751        self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({'class': 'required'}, {'class': 'required'}))
 752        f = Person(names_required=False)
 753        self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
 754        self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
 755
 756        class Person(Form):
 757            first_name = CharField(max_length=30)
 758            last_name = CharField(max_length=30)
 759
 760            def __init__(self, name_max_length=None, *args, **kwargs):
 761                super(Person, self).__init__(*args, **kwargs)
 762
 763                if name_max_length:
 764                    self.fields['first_name'].max_length = name_max_length
 765                    self.fields['last_name'].max_length = name_max_length
 766
 767        f = Person(name_max_length=None)
 768        self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
 769        f = Person(name_max_length=20)
 770        self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (20, 20))
 771        f = Person(name_max_length=None)
 772        self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
 773
 774    def test_hidden_widget(self):
 775        # HiddenInput widgets are displayed differently in the as_table(), as_ul())
 776        # and as_p() output of a Form -- their verbose names are not displayed, and a
 777        # separate row is not displayed. They're displayed in the last row of the
 778        # form, directly after that row's form element.
 779        class Person(Form):
 780            first_name = CharField()
 781            last_name = CharField()
 782            hidden_text = CharField(widget=HiddenInput)
 783            birthday = DateField()
 784
 785        p = Person(auto_id=False)
 786        self.assertEqual(p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr>
 787<tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr>
 788<tr><th>Birthday:</th><td><input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></td></tr>""")
 789        self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
 790<li>Last name: <input type="text" name="last_name" /></li>
 791<li>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></li>""")
 792        self.assertEqual(p.as_p(), """<p>First name: <input type="text" name="first_name" /></p>
 793<p>Last name: <input type="text" name="last_name" /></p>
 794<p>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></p>""")
 795
 796        # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
 797        p = Person(auto_id='id_%s')
 798        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>
 799<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
 800<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>""")
 801        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>
 802<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
 803<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>""")
 804        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>
 805<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
 806<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></p>""")
 807
 808        # If a field with a HiddenInput has errors, the as_table() and as_ul() output
 809        # will include the error message(s) with the text "(Hidden field [fieldname]) "
 810        # prepended. This message is displayed at the top of the output, regardless of
 811        # its field's order in the form.
 812        p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False)
 813        self.assertEqual(p.as_table(), """<tr><td colspan="2"><ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul></td></tr>
 814<tr><th>First name:</th><td><input type="text" name="first_name" value="John" /></td></tr>
 815<tr><th>Last name:</th><td><input type="text" name="last_name" value="Lennon" /></td></tr>
 816<tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></td></tr>""")
 817        self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul></li>
 818<li>First name: <input type="text" name="first_name" value="John" /></li>
 819<li>Last name: <input type="text" name="last_name" value="Lennon" /></li>
 820<li>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></li>""")
 821        self.assertEqual(p.as_p(), """<ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul>
 822<p>First name: <input type="text" name="first_name" value="John" /></p>
 823<p>Last name: <input type="text" name="last_name" value="Lennon" /></p>
 824<p>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></p>""")
 825
 826        # A corner case: It's possible for a form to have only HiddenInputs.
 827        class TestForm(Form):
 828            foo = CharField(widget=HiddenInput)
 829            bar = CharField(widget=HiddenInput)
 830
 831        p = TestForm(auto_id=False)
 832        self.assertEqual(p.as_table(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
 833        self.assertEqual(p.as_ul(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
 834        self.assertEqual(p.as_p(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
 835
 836    def test_field_order(self):
 837        # A Form's fields are displayed in the same order in which they were defined.
 838        class TestForm(Form):
 839            field1 = CharField()
 840            field2 = CharField()
 841            field3 = CharField()
 842            field4 = CharField()
 843            field5 = CharField()
 844            field6 = CharField()
 845            field7 = CharField()
 846            field8 = CharField()
 847            field9 = CharField()
 848            field10 = CharField()
 849            field11 = CharField()
 850            field12 = CharField()
 851            field13 = CharField()
 852            field14 = CharField()
 853
 854        p = TestForm(auto_id=False)
 855        self.assertEqual(p.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
 856<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>
 857<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
 858<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>
 859<tr><th>Field5:</th><td><input type="text" name="field5" /></td></tr>
 860<tr><th>Field6:</th><td><input type="text" name="field6" /></td></tr>
 861<tr><th>Field7:</th><td><input type="text" name="field7" /></td></tr>
 862<tr><th>Field8:</th><td><input type="text" name="field8" /></td></tr>
 863<tr><th>Field9:</th><td><input type="text" name="field9" /></td></tr>
 864<tr><th>Field10:</th><td><input type="text" name="field10" /></td></tr>
 865<tr><th>Field11:</th><td><input type="text" name="field11" /></td></tr>
 866<tr><th>Field12:</th><td><input type="text" name="field12" /></td></tr>
 867<tr><th>Field13:</th><td><input type="text" name="field13" /></td></tr>
 868<tr><th>Field14:</th><td><input type="text" name="field14" /></td></tr>""")
 869
 870    def test_form_html_attributes(self):
 871        # Some Field classes have an effect on the HTML attributes of their associated
 872        # Widget. If you set max_length in a CharField and its associated widget is
 873        # either a TextInput or PasswordInput, then the widget's rendered HTML will
 874        # include the "maxlength" attribute.
 875        class UserRegistration(Form):
 876            username = CharField(max_length=10)                   # uses TextInput by default
 877            password = CharField(max_length=10, widget=PasswordInput)
 878            realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test
 879            address = CharField()                                 # no max_length defined here
 880
 881        p = UserRegistration(auto_id=False)
 882        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li>
 883<li>Password: <input type="password" name="password" maxlength="10" /></li>
 884<li>Realname: <input type="text" name="realname" maxlength="10" /></li>
 885<li>Address: <input type="text" name="address" /></li>""")
 886
 887        # If you specify a custom "attrs" that includes the "maxlength" attribute,
 888        # the Field's max_length attribute will override whatever "maxlength" you specify
 889        # in "attrs".
 890        class UserRegistration(Form):
 891            username = CharField(max_length=10, widget=TextInput(attrs={'maxlength': 20}))
 892            password = CharField(max_length=10, widget=PasswordInput)
 893
 894        p = UserRegistration(auto_id=False)
 895        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li>
 896<li>Password: <input type="password" name="password" maxlength="10" /></li>""")
 897
 898    def test_specifying_labels(self):
 899        # You can specify the label for a field by using the 'label' argument to a Field
 900        # class. If you don't specify 'label', Django will use the field name with
 901        # underscores converted to spaces, and the initial letter capitalized.
 902        class UserRegistration(Form):
 903            username = CharField(max_length=10, label='Your username')
 904            password1 = CharField(widget=PasswordInput)
 905            password2 = CharField(widget=PasswordInput, label='Password (again)')
 906
 907        p = UserRegistration(auto_id=False)
 908        self.assertEqual(p.as_ul(), """<li>Your username: <input type="text" name="username" maxlength="10" /></li>
 909<li>Password1: <input type="password" name="password1" /></li>
 910<li>Password (again): <input type="password" name="password2" /></li>""")
 911
 912        # Labels for as_* methods will only end in a colon if they don't end in other
 913        # punctuation already.
 914        class Questions(Form):
 915            q1 = CharField(label='The first question')
 916            q2 = CharField(label='What is your name?')
 917            q3 = CharField(label='The answer to life is:')
 918            q4 = CharField(label='Answer this question!')
 919            q5 = CharField(label='The last question. Period.')
 920
 921        self.assertEqual(Questions(auto_id=False).as_p(), """<p>The first question: <input type="text" name="q1" /></p>
 922<p>What is your name? <input type="text" name="q2" /></p>
 923<p>The answer to life is: <input type="text" name="q3" /></p>
 924<p>Answer this question! <input type="text" name="q4" /></p>
 925<p>The last question. Period. <input type="text" name="q5" /></p>""")
 926        self.assertEqual(Questions().as_p(), """<p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" /></p>
 927<p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" /></p>
 928<p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" /></p>
 929<p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" /></p>
 930<p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" /></p>""")
 931
 932        # A label can be a Unicode object or a bytestring with special characters.
 933        class UserRegistration(Form):
 934            username = CharField(max_length=10, label='Š??Ž?žš?')
 935            password = CharField(widget=PasswordInput, label=u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111')
 936
 937        p = UserRegistration(auto_id=False)
 938        self.assertEqual(p.as_ul(), u'<li>\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111: <input type="text" name="username" maxlength="10" /></li>\n<li>\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111: <input type="password" name="password" /></li>')
 939
 940        # If a label is set to the empty string for a field, that field won't get a label.
 941        class UserRegistration(Form):
 942            username = CharField(max_length=10, label='')
 943            password = CharField(widget=PasswordInput)
 944
 945        p = UserRegistration(auto_id=False)
 946        self.assertEqual(p.as_ul(), """<li> <input type="text" name="username" maxlength="10" /></li>
 947<li>Password: <input type="password" name="password" /></li>""")
 948        p = UserRegistration(auto_id='id_%s')
 949        self.assertEqual(p.as_ul(), """<li> <input id="id_username" type="text" name="username" maxlength="10" /></li>
 950<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>""")
 951
 952        # If label is None, Django will auto-create the label from the field name. This
 953        # is default behavior.
 954        class UserRegistration(Form):
 955            username = CharField(max_length=10, label=None)
 956            password = CharField(widget=PasswordInput)
 957
 958        p = UserRegistration(auto_id=False)
 959        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li>
 960<li>Password: <input type="password" name="password" /></li>""")
 961        p = UserRegistration(auto_id='id_%s')
 962        self.assertEqual(p.as_ul(), """<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></li>
 963<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>""")
 964
 965    def test_label_suffix(self):
 966        # You can specify the 'label_suffix' argument to a Form class to modify the
 967        # punctuation symbol used at the end of a label.  By default, the colon (:) is
 968        # used, and is only appended to the label if the label doesn't already end with a
 969        # punctuation symbol: ., !, ? or :.  If you specify a different suffix, it will
 970        # be appended regardless of the last character of the label.
 971        class FavoriteForm(Form):
 972            color = CharField(label='Favorite color?')
 973            animal = CharField(label='Favorite animal')
 974
 975        f = FavoriteForm(auto_id=False)
 976        self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li>
 977<li>Favorite animal: <input type="text" name="animal" /></li>""")
 978        f = FavoriteForm(auto_id=False, label_suffix='?')
 979        self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li>
 980<li>Favorite animal? <input type="text" name="animal" /></li>""")
 981        f = FavoriteForm(auto_id=False, label_suffix='')
 982        self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li>
 983<li>Favorite animal <input type="text" name="animal" /></li>""")
 984        f = FavoriteForm(auto_id=False, label_suffix=u'\u2192')
 985        self.assertEqual(f.as_ul(), u'<li>Favorite color? <input type="text" name="color" /></li>\n<li>Favorite animal\u2192 <input type="text" name="animal" /></li>')
 986
 987    def test_initial_data(self):
 988        # You can specify initial data for a field by using the 'initial' argument to a
 989        # Field class. This initial data is displayed when a Form is rendered with *no*
 990        # data. It is not displayed when a Form is rendered with any data (including an
 991        # empty dictionary). Also, the initial value is *not* used if data for a
 992        # particular required field isn't provided.
 993        class UserRegistration(Form):
 994            username = CharField(max_length=10, initial='django')
 995            password = CharField(widget=PasswordInput)
 996
 997        # Here, we're not submitting any data, so the initial value will be displayed.)
 998        p = UserRegistration(auto_id=False)
 999        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
1000<li>Password: <input type="password" name="password" /></li>""")
1001
1002        # Here, we're submitting data, so the initial value will *not* be displayed.
1003        p = UserRegistration({}, auto_id=False)
1004        self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
1005<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
1006        p = UserRegistration({'username': u''}, auto_id=False)
1007        self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
1008<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
1009        p = UserRegistration({'username': u'foo'}, auto_id=False)
1010        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
1011<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
1012
1013        # An 'initial' value is *not* used as a fallback if data is not provided. In this
1014        # example, we don't provide a value for 'username', and the form raises a
1015        # validation error rather than using the initial value for 'username'.
1016        p = UserRegistration({'password': 'secret'})
1017        self.assertEqual(p.errors['username'], [u'This field is required.'])
1018        self.assertFalse(p.is_valid())
1019
1020    def test_dynamic_initial_data(self):
1021        # The previous technique dealt with "hard-coded" initial data, but it's also
1022        # possible to specify initial data after you've already created the Form class
1023        # (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This
1024        # should be a dictionary containing initial values for one or more fields in the
1025        # form, keyed by field name.
1026        class UserRegistration(Form):
1027            username = CharField(max_length=10)
1028            password = CharField(widget=PasswordInput)
1029
1030        # Here, we're not submitting any data, so the initial value will be displayed.)
1031        p = UserRegistration(initial={'username': 'django'}, auto_id=False)
1032        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
1033<li>Password: <input type="password" name="password" /></li>""")
1034        p = UserRegistration(initial={'username': 'stephane'}, auto_id=False)
1035        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li>
1036<li>Password: <input type="password" name="password" /></li>""")
1037
1038        # The 'initial' parameter is meaningless if you pass data.
1039        p = UserRegistration({}, initial={'username': 'django'}, auto_id=False)
1040        self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
1041<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
1042        p = UserRegistration({'username': u''}, initial={'username': 'django'}, auto_id=False)
1043        self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
1044<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
1045        p = UserRegistration({'username': u'foo'}, initial={'username': 'django'}, auto_id=False)
1046        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
1047<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""")
1048
1049        # A dynamic 'initial' value is *not* used as a fallback if data is not provided.
1050        # In this example, we don't provide a value for 'username', and the form raises a
1051        # validation error rather than using the initial value for 'username'.
1052        p = UserRegistration({'password': 'secret'}, initial={'username': 'django'})
1053        self.assertEqual(p.errors['username'], [u'This field is required.'])
1054        self.assertFalse(p.is_valid())
1055
1056        # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
1057        # then the latter will get precedence.
1058        class UserRegistration(Form):
1059            username = CharField(max_length=10, initial='django')
1060            password = CharField(widget=PasswordInput)
1061
1062        p = UserRegistration(initial={'username': 'babik'}, auto_id=False)
1063        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="babik" maxlength="10" /></li>
1064<li>Password: <input type="password" name="password" /></li>""")
1065
1066    def test_callable_initial_data(self):
1067        # The previous technique dealt with raw values as initial data, but it's also
1068        # possible to specify callable data.
1069        class UserRegistration(Form):
1070            username = CharField(max_length=10)
1071            password = CharField(widget=PasswordInput)
1072            options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')])
1073
1074        # We need to define functions that get called later.)
1075        def initial_django():
1076            return 'django'
1077
1078        def initial_stephane():
1079            return 'stephane'
1080
1081        def initial_options():
1082            return ['f','b']
1083
1084        def initial_other_options():
1085            return ['b','w']
1086
1087        # Here, we're not submitting any data, so the initial value will be displayed.)
1088        p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False)
1089        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
1090<li>Password: <input type="password" name="password" /></li>
1091<li>Options: <select multiple="multiple" name="options">
1092<option value="f" selected="selected">foo</option>
1093<option value="b" selected="selected">bar</option>
1094<option value="w">whiz</option>
1095</select></li>""")
1096
1097        # The 'initial' parameter is meaningless if you pass data.
1098        p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False)
1099        self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
1100<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
1101<li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options">
1102<option value="f">foo</option>
1103<option value="b">bar</option>
1104<option value="w">whiz</option>
1105</select></li>""")
1106        p = UserRegistration({'username': u''}, initial={'username': initial_django}, auto_id=False)
1107        self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
1108<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
1109<li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options">
1110<option value="f">foo</option>
1111<option value="b">bar</option>
1112<option value="w">whiz</option>
1113</select></li>""")
1114        p = UserRegistration({'username': u'foo', 'options':['f','b']}, initial={'username': initial_django}, auto_id=False)
1115        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
1116<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
1117<li>Options: <select multiple="multiple" name="options">
1118<option value="f" selected="selected">foo</option>
1119<option value="b" selected="selected">bar</option>
1120<option value="w">whiz</option>
1121</select></li>""")
1122
1123        # A callable 'initial' value is *not* used as a fallback if data is not provided.
1124        # In this example, we don't provide a value for 'username', and the form raises a
1125        # validation error rather than using the initial value for 'username'.
1126        p = UserRegistration({'password': 'secret'}, initial={'username': initial_django, 'options': initial_options})
1127        self.assertEqual(p.errors['username'], [u'This field is required.'])
1128        self.assertFalse(p.is_valid())
1129
1130        # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
1131        # then the latter will get precedence.
1132        class UserRegistration(Form):
1133           username = CharField(max_length=10, initial=initial_django)
1134           password = CharField(widget=PasswordInput)
1135           options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')], initial=initial_other_options)
1136
1137        p = UserRegistration(auto_id=False)
1138        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
1139<li>Password: <input type="password" name="password" /></li>
1140<li>Options: <select multiple="multiple" name="options">
1141<option value="f">foo</option>
1142<option value="b" selected="selected">bar</option>
1143<option value="w" selected="selected">whiz</option>
1144</select></li>""")
1145        p = UserRegistration(initial={'username': initial_stephane, 'options': initial_options}, auto_id=False)
1146        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li>
1147<li>Password: <input type="password" name="password" /></li>
1148<li>Options: <select multiple="multiple" name="options">
1149<option value="f" selected="selected">foo</option>
1150<option value="b" selected="selected">bar</option>
1151<option value="w">whiz</option>
1152</select></li>""")
1153
1154    def test_boundfield_values(self):
1155        # It's possible to get to the value which would be used for rendering
1156        # the widget for a field by using the BoundField's value method.
1157 
1158        class UserRegistration(Form):
1159            username = CharField(max_length=10, initial='djangonaut')
1160            password = CharField(widget=PasswordInput)
1161
1162        unbound = UserRegistration()
1163        bound = UserRegistration({'password': 'foo'})
1164        self.assertEqual(bound['username'].value(), None)
1165        self.assertEqual(unbound['username'].value(), 'djangonaut')
1166        self.assertEqual(bound['password'].value(), 'foo')
1167        self.assertEqual(unbound['password'].value(), None)
1168
1169    def test_help_text(self):
1170        # You can specify descriptive text for a field by using the 'help_text' argument)
1171        class UserRegistration(Form):
1172            username = CharField(max_length=10, help_text='e.g., user@example.com')
1173            password = CharField(widget=PasswordInput, help_text='Choose wisely.')
1174
1175        p = UserRegistration(auto_id=False)
1176        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li>
1177<li>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></li>""")
1178        self.assertEqual(p.as_p(), """<p>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></p>
1179<p>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></p>""")
1180        self.assertEqual(p.as_table(), """<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" /><br /><span class="helptext">e.g., user@example.com</span></td></tr>
1181<tr><th>Password:</th><td><input type="password" name="password" /><br /><span class="helptext">Choose wisely.</span></td></tr>""")
1182
1183        # The help text is displayed whether or not data is provided for the form.
1184        p = UserRegistration({'username': u'foo'}, auto_id=False)
1185        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li>
1186<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></li>""")
1187
1188        # help_text is not displayed for hidden fields. It can be used for documentation
1189        # purposes, though.
1190        class UserRegistration(Form):
1191            username = CharField(max_length=10, help_text='e.g., user@example.com')
1192            password = CharField(widget=PasswordInput)
1193            next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination')
1194
1195        p = UserRegistration(auto_id=False)
1196        self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li>
1197<li>Password: <input type="password" name="password" /><input type="hidden" name="next" value="/" /></li>""")
1198
1199        # Help text can include arbitrary Unicode characters.
1200        class UserRegistration(Form):
1201            username = CharField(max_length=10, help_text='Š??Ž?žš?')
1202
1203        p = UserRegistration(auto_id=False)
1204        self.assertEqual(p.as_ul(), u'<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111</span></li>')
1205
1206    def test_subclassing_forms(self):
1207        # You can subclass a Form to add fields. The resulting form subclass will have
1208        # all of the fields of the parent Form, plus whichever fields you define in the
1209        # subclass.
1210        class Person(Form):
1211            first_name = CharField()
1212            last_name = CharField()
1213            birthday = DateField()
1214
1215        class Musician(Person):
1216            instrument = CharField()
1217
1218        p = Person(auto_id=False)
1219        self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
1220<li>Last name: <input type="text" name="last_name" /></li>
1221<li>Birthday: <input type="text" name="birthday" /></li>""")
1222        m = Musician(auto_id=False)
1223        self.assertEqual(m.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
1224<li>Last name: <input type="text" name="last_name" /></li>
1225<li>Birthday: <input type="text" name="birthday" /></li>
1226<li>Instrument: <input type="text" name="instrument" /></li>""")
1227
1228        # Yes, you can subclass multiple forms. The fields are added in the order in
1229        # which the parent classes are listed.
1230        class Person(Form):
1231            first_name = CharField()
1232            last_name = CharField()
1233            birthday = DateField()
1234
1235        class Instrument(Form):
1236            instrument = CharField()
1237
1238        class Beatle(Person, Instrument):
1239            haircut_type = CharField()
1240
1241        b = Beatle(auto_id=False)
1242        self.assertEqual(b.as_ul(), """<li>First name: <input type="text" name="first_name" /></li>
1243<li>Last name: <input type="text" name="last_name" /></li>
1244<li>Birthday: <input type="text" name="birthday" /></li>
1245<li>Instrument: <input type="text" name="instrument" /></li>
1246<li>Haircut type: <input type="text" name="haircut_type" /></li>""")
1247
1248    def test_forms_with_prefixes(self):
1249        # Sometimes it's necessary to have multiple forms display on the same HTML page,
1250        # or multiple copies of the same form. We can accomplish this with form prefixes.
1251        # Pass the keyword argument 'prefix' to the Form constructor to use this feature.
1252        # This value will be prepended to each HTML form field name. One way to think
1253        # about this is "namespaces for HTML forms". Notice that in the data argument,
1254        # each field's key has the prefix, in this case 'person1', prepended to the
1255        # actual field name.
1256        class Person(Form):
1257            first_name = CharField()
1258            last_name = CharField()
1259            birthday = DateField()
1260
1261        data = {
1262            'person1-first_name': u'John',
1263            'person1-last_name': u'Lennon',
1264            'person1-birthday': u'1940-10-9'
1265        }
1266        p = Person(data, prefix='person1')
1267        self.assertEqual(p.as_ul(), """<li><label for="id_person1-first_name">First name:</label> <input type="text" name="person1-first_name" value="John" id="id_person1-first_name" /></li>
1268<li><label for="id_person1-last_name">Last name:</label> <input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" /></li>
1269<li><label for="id_person1-birthday">Birthday:</label> <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" /></li>""")
1270        self.assertEqual(str(p['first_name']), '<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" />')
1271        self.assertEqual(str(p['last_name']), '<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" />')
1272        self.assertEqual(str(p['birthday']), '<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" />')
1273        self.assertEqual(p.errors, {})
1274        self.assertTrue(p.is_valid())
1275        self.assertEqual(p.cleaned_data['first_name'], u'John')
1276        self.assertEqual(p.cleaned_data['last_name'], u'Lennon')
1277        self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
1278
1279        # Let's try submitting some bad data to make sure form.errors and field.errors
1280        # work as expected.
1281        data = {
1282            'person1-first_name': u'',
1283            'person1-last_name': u'',
1284            'person1-birthday': u''
1285        }
1286        p = Person(data, prefix='person1')
1287        self.assertEqual(p.errors['first_name'], [u'This field is required.'])
1288        self.assertEqual(p.errors['last_name'], [u'This field is required.'])
1289        self.assertEqual(p.errors['birthday'], [u'This field is required.'])
1290        self.assertEqual(p['first_name'].errors, [u'This field is required.'])
1291        try:
1292            p['person1-first_name'].errors
1293            self.fail('Attempts to access non-existent fields should fail.')
1294        except KeyError:
1295            pass
1296
1297        # In this example, the data doesn't have a prefix, but the form requires it, so
1298        # the form doesn't "see" the fields.
1299        data = {
1300            'first_name': u'John',
1301            'last_name': u'Lennon',
1302            'birthday': u'1940-10-9'
1303        }
1304        p = Person(data, prefix='person1')
1305        self.assertEqual(p.errors['first_name'], [u'This field is required.'])
1306        self.assertEqual(p.errors['last_name'], [u'This field is required.'])
1307        self.assertEqual(p.errors['birthday'], [u'This field is required.'])
1308
1309        # With prefixes, a single data dictionary can hold data for multiple instances
1310        # of the same form.
1311        data = {
1312            'person1-first_name': u'John',
1313            'person1-last_name': u'Lennon',
1314            'person1-birthday': u'1940-10-9',
1315            'person2-first_name': u'Jim',
1316            'person2-last_name': u'Morrison',
1317            'person2-birthday': u'1943-12-8'
1318        }
1319        p1 = Person(data, prefix='person1')
1320        self.assertTrue(p1.is_valid())
1321        self.assertEqual(p1.cleaned_data['first_name'], u'John')
1322        self.assertEqual(p1.cleaned_data['last_name'], u'Lennon')
1323        self.assertEqual(p1.cleaned_data['birthday'], datetime.date(1940, 10, 9))
1324        p2 = Person(data, prefix='person2')
1325        self.assertTrue(p2.is_valid())
1326        self.assertEqual(p2.cleaned_data['first_name'], u'Jim')
1327        self.assertEqual(p2.cleaned_data['last_name'], u'Morrison')
1328        self.assertEqual(p2.cleaned_data['birthday'], datetime.date(1943, 12, 8))
1329
1330        # By default, forms append a hyphen between the prefix and the field name, but a
1331        # form can alter that behavior by implementing the add_prefix() method. This
1332        # method takes a field name and returns the prefixed field, according to
1333        # self.prefix.
1334        class Person(Form):
1335            first_name = CharField()
1336            last_name = CharField()
1337            birthday = DateField()
1338
1339            def add_prefix(self, field_name):
1340                return self.prefix and '%s-prefix-%s' % (self.prefix, field_name) or field_name
1341
1342        p = Person(prefix='foo')
1343        self.assertEqual(p.as_ul(), """<li><label for="id_foo-prefix-first_name">First name:</label> <input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" /></li>
1344<li><label for="id_foo-prefix-last_name">Last name:</label> <input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" /></li>
1345<li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" /></li>""")
1346        data = {
1347            'foo-prefix-first_name': u'John',
1348            'foo-prefix-last_name': u'Lennon',
1349            'foo-prefix-birthday': u'1940-10-9'
1350        }
1351        p = Person(data, prefix='foo')
1352        self.assertTrue(p.is_valid())
1353        self.assertEqual(p.cleaned_data['first_name'], u'John')
1354        self.assertEqual(p.cleaned_data['last_name'], u'Lennon')
1355        self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
1356
1357    def test_forms_with_null_boolean(self):
1358        # NullBooleanField is a bit of a special case because its presentation (widget)
1359        # is different than its data. This is handled transparently, though.
1360        class Person(Form):
1361            name = CharField()
1362            is_cool = NullBooleanField()
1363
1364        p = Person({'name': u'Joe'}, auto_id=False)
1365        self.assertEqual(str(p['is_cool']), """<select name="is_cool">
1366<option value="1" selected="selected">Unknown</option>
1367<option value="2">Yes</option>
1368<option value="3">No</option>
1369</select>""")
1370        p = Person({'name': u'Joe', 'is_cool': u'1'}, auto_id=False)
1371        self.assertEqual(str(p['is_cool']), """<select name="is_cool">
1372<option value="1" selected="selected">Unknown</option>
1373<option value="2">Yes</option>
1374<option value="3">No</option>
1375</select>""")
1376        p = Person({'name': u'Joe', 'is_cool': u'2'}, auto_id=False)
1377        self.assertEqual(str(p['is_cool']), """<select name="is_cool">
1378<option value="1">Unknown</option>
1379<option value="2" selected="selected">Yes</option>
1380<option value="3">No</option>
1381</select>""")
1382        p = Person({'name': u'Joe', 'is_cool': u'3'}, auto_id=False)
1383        self.assertEqual(str(p['is_cool']), """<select name="is_cool">
1384<option value="1">Unknown</option>
1385<option value="2">Yes</option>
1386<option value="3" selected="selected">No</option>
1387</select>""")
1388        p = Person({'name': u'Joe', 'is_cool': True}, auto_id=False)
1389        self.assertEqual(str(p['is_cool']), """<select name="is_cool">
1390<option value="1">Unknown</option>
1391<option value="2" selected="selected">Yes</option>
1392<option value="3">No</option>
1393</select>""")
1394        p = Person({'name': u'Joe', 'is_cool': False}, auto_id=False)
1395        self.assertEqual(str(p['is_cool']), """<select name="is_cool">
1396<option value="1">Unknown</option>
1397<option value="2">Yes</option>
1398<option value="3" selected="selected">No</option>
1399</select>""")
1400
1401    def test_forms_with_file_fields(self):
1402        # FileFields are a special case because they take their data from the request.FILES,
1403        # not request.POST.
1404        class FileForm(Form):
1405            file1 = FileField()
1406
1407        f = FileForm(auto_id=False)
1408        self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
1409
1410        f = FileForm(data={}, files={}, auto_id=False)
1411        self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="file" name="file1" /></td></tr>')
1412
1413        f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', '')}, auto_id=False)
1414        self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><ul class="errorlist"><li>The submitted file is empty.</li></ul><input type="file" name="file1" /></td></tr>')
1415
1416        f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False)
1417        self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><ul class="errorlist"><li>No file was submitted. Check the encoding type on the form.</li></ul><input type="file" name="file1" /></td></tr>')
1418
1419        f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', 'some content')}, auto_id=False)
1420        self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
1421        self.assertTrue(f.is_valid())
1422
1423        f = FileForm(data={}, files={'file1': SimpleUploadedFile('?????????.txt', '???? ??????? ???? ??? ????????? ?? ??? ?')}, auto_id=False)
1424        self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
1425
1426    def test_basic_processing_in_view(self):
1427        class UserRegistration(Form):
1428            username = CharField(max_length=10)
1429            password1 = CharField(widget=PasswordInput)
1430            password2 = CharField(widget=PasswordInput)
1431
1432            def clean(self):
1433                if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
1434                    raise ValidationError(u'Please make sure your passwords match.')
1435
1436                return self.cleaned_data
1437
1438        def my_function(method, post_data):
1439            if method == 'POST':
1440                form = UserRegistration(post_data, auto_id=False)
1441            else:
1442                form = UserRegistration(auto_id=False)
1443
1444            if form.is_valid():
1445                return 'VALID: %r' % form.cleaned_data
1446
1447            t = Template('<form action="" method="post">\n<table>\n{{ form }}\n</table>\n<input type="submit" />\n</form>')
1448            return t.render(Context({'form': form}))
1449
1450        # Case 1: GET (an empty form, with no errors).)
1451        self.assertEqual(my_function('GET', {}), """<form action="" method="post">
1452<table>
1453<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" /></td></tr>
1454<tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr>
1455<tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>
1456</table>
1457<input type="submit" />
1458</form>""")
1459        # Case 2: POST with erroneous data (a redisplayed form, with errors).)
1460        self.assertEqual(my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}), """<form action="" method="post">
1461<table>
1462<tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr>
1463<tr><th>Username:</th><td><ul class="errorlist"><li>Ensure this value has at most 10 characters (it has 23).</li></ul><input type="text" name="username" value="this-is-a-long-username" maxlength="10" /></td></tr>
1464<tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr>
1465<tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>
1466</table>
1467<input type="submit" />
1468</form>""")
1469        # Case 3: POST with valid data (the success message).)
1470        self.assertEqual(my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}), "VALID: {'username': u'adrian', 'password1': u'secret', 'password2': u'secret'}")
1471
1472    def test_templates_with_forms(self):
1473        class UserRegistration(Form):
1474            username = CharField(max_length=10, help_text="Good luck picking a username that doesn't already exist.")
1475            password1 = CharField(widget=PasswordInput)
1476            password2 = CharField(widget=PasswordInput)
1477
1478            def clean(self):
1479                if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
1480                    raise ValidationError(u'Please make sure your passwords match.')
1481
1482                return self.cleaned_data
1483
1484        # You have full flexibility in displaying form fields in a template. Just pass a
1485        # Form instance to the template, and use "dot" access to refer to individual
1486        # fields. Note, however, that this flexibility comes with the responsibility of
1487        # displaying all the errors, including any that might not be associated with a
1488        # particular field.
1489        t = Template('''<form action="">
1490{{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
1491{{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
1492{{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
1493<input type="submit" />
1494</form>''')
1495        self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
1496<p><label>Your username: <input type="text" name="username" maxlength="10" /></label></p>
1497<p><label>Password: <input type="password" name="password1" /></label></p>
1498<p><label>Password (again): <input type="password" name="password2" /></label></p>
1499<input type="submit" />
1500</form>""")
1501        self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})), """<form action="">
1502<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
1503<ul class="errorlist"><li>This field is required.</li></ul><p><label>Password: <input type="password" name="password1" /></label></p>
1504<ul class="errorlist"><li>This field is required.</li></ul><p><label>Password (again): <input type="password" name="password2" /></label></p>
1505<input type="submit" />
1506</form>""")
1507
1508        # Use form.[field].label to output a field's label. You can specify the label for
1509        # a field by using the 'label' argument to a Field class. If you don't specify
1510        # 'label', Django will use the field name with underscores converted to spaces,
1511        # and the initial letter capitalized.
1512        t = Template('''<form action="">
1513<p><label>{{ form.username.label }}: {{ form.username }}</label></p>
1514<p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p>
1515<p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p>
1516<input type="submit" />
1517</form>''')
1518        self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
1519<p><label>Username: <input type="text" name="username" maxlength="10" /></label></p>
1520<p><label>Password1: <input type="password" name="password1" /></label></p>
1521<p><label>Password2: <input type="password" name="password2" /></label></p>
1522<input type="submit" />
1523</form>""")
1524
1525        # User form.[field].label_tag to output a field's label with a <label> tag
1526        # wrapped around it, but *only* if the given field has an "id" attribute.
1527        # Recall from above that passing the "auto_id" argument to a Form gives each
1528        # field an "id" attribute.
1529        t = Template('''<form action="">
1530<p>{{ form.username.label_tag }}: {{ form.username }}</p>
1531<p>{{ form.password1.label_tag }}: {{ form.password1 }}</p>
1532<p>{{ form.password2.label_tag }}: {{ form.password2 }}</p>
1533<input type="submit" />
1534</form>''')
1535        self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
1536<p>Username: <input type="text" name="username" maxlength="10" /></p>
1537<p>Password1: <input type="password" name="password1" /></p>
1538<p>Password2: <input type="password" name="password2" /></p>
1539<input type="submit" />
1540</form>""")
1541        self.assertEqual(t.render(Context({'form': UserRegistration(auto_id='id_%s')})), """<form action="">
1542<p><label for="id_username">Username</label>: <input id="id_username" type="text" name="username" maxlength="10" /></p>
1543<p><label for="id_password1">Password1</label>: <input type="password" name="password1" id="id_password1" /></p>
1544<p><label for="id_password2">Password2</label>: <input type="password" name="password2" id="id_password2" /></p>
1545<input type="submit" />
1546</form>""")
1547
1548        # User form.[field].help_text to output a field's help text. If the given field
1549        # does not have help text, nothing will be output.
1550        t = Template('''<form action="">
1551<p>{{ form.username.label_tag }}: {{ form.username }}<br />{{ form.username.help_text }}</p>
1552<p>{{ form.password1.label_tag }}: {{ form.password1 }}</p>
1553<p>{{ form.password2.label_tag }}: {{ form.password2 }}</p>
1554<input type="submit" />
1555</form>''')
1556        self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action="">
1557<p>Username: <input type="text" name="username" maxlength="10" /><br />Good luck picking a username that doesn&#39;t already exist.</p>
1558<p>Password1: <input type="password" name="password1" /></p>
1559<p>Password2: <input type="password" name="password2" /></p>
1560<input type="submit" />
1561</form>""")
1562        self.assertEqual(Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})), u'')
1563
1564        # The label_tag() method takes an optional attrs argument: a dictionary of HTML
1565        # attributes to add to the <label> tag.
1566        f = UserRegistration(auto_id='id_%s')
1567        form_output = []
1568
1569        for bf in f:
1570            form_output.append(bf.label_tag(attrs={'class': 'pretty'}))
1571
1572        self.assertEqual(form_output, [
1573            '<label for="id_username" class="pretty">Username</label>',
1574            '<label for="id_password1" class="pretty">Password1</label>',
1575            '<label for="id_password2" class="pretty">Password2</label>',
1576        ])
1577
1578        # To display the errors that aren't associated with a particular field -- e.g.,
1579        # the errors caused by Form.clean() -- use {{ form.non_field_errors }} in the
1580        # template. If used on its own, it is displayed as a <ul> (or an empty string, if
1581        # the list of errors is empty). You can also use it in {% if %} statements.
1582        t = Template('''<form action="">
1583{{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
1584{{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
1585{{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
1586<input type="submit" />
1587</form>''')
1588        self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """<form action="">
1589<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
1590<p><label>Password: <input type="password" name="password1" /></label></p>
1591<p><label>Password (again): <input type="password" name="password2" /></label></p>
1592<input type="submit" />
1593</form>""")
1594        t = Template('''<form action="">
1595{{ form.non_field_errors }}
1596{{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
1597{{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
1598{{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
1599<input type="submit" />
1600</form>''')
1601        self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """<form action="">
1602<ul class="errorlist"><li>Please make sure your passwords match.</li></ul>
1603<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
1604<p><label>Password: <input type="password" name="password1" /></label></p>
1605<p><label>Password (again): <input type="password" name="password2" /></label></p>
1606<input type="submit" />
1607</form>""")
1608
1609    def test_empty_permitted(self):
1610        # Sometimes (pretty much in formsets) we want to allow a form to pass validation
1611        # if it is completely empty. We can accomplish this by using the empty_permitted
1612        # agrument to a form constructor.
1613        class SongForm(Form):
1614            artist = CharField()
1615            name = CharField()
1616
1617        # First let's show what happens id empty_permitted=False (the default):
1618        data = {'artist': '', 'song': ''}
1619        form = SongForm(data, empty_permitted=False)
1620        self.assertFalse(form.is_valid())
1621        self.assertEqual(form.errors, {'name': [u'This field is required.'], 'artist': [u'This field is required.']})
1622        try:
1623            form.cleaned_data
1624            self.fail('Attempts to access cleaned_data when validation fails should fail.')
1625        except AttributeError:
1626            pass
1627
1628        # Now let's show what happens when empty_permitted=True and the form is empty.
1629        form = SongForm(data, empty_permitted=True)
1630        self.assertTrue(form.is_valid())
1631        self.assertEqual(form.errors, {})
1632        self.assertEqual(form.cleaned_data, {})
1633
1634        # But if we fill in data for one of the fields, the form is no longer empty and
1635        # the whole thing must pass validation.
1636        data = {'artist': 'The Doors', 'song': ''}
1637        form = SongForm(data, empty_permitted=False)
1638        self.assertFalse(form.is_valid())
1639        self.assertEqual(form.errors, {'name': [u'This field is required.']})
1640        try:
1641            form.cleaned_data
1642            self.fail('Attempts to access cleaned_data when validation fails should fail.')
1643        except AttributeError:
1644            pass
1645
1646        # If a field is not given in the data then None is returned for its data. Lets
1647        # make sure that when checking for empty_permitted that None is treated
1648        # accordingly.
1649        data = {'artist': None, 'song': ''}
1650        form = SongForm(data, empty_permitted=True)
1651        self.assertTrue(form.is_valid())
1652
1653        # However, we *really* need to be sure we are checking for None as any data in
1654        # initial that returns False on a boolean call needs to be treated literally.
1655        class PriceForm(Form):
1656            amount = FloatField()
1657            qty = IntegerField()
1658
1659        data = {'amount': '0.0', 'qty': ''}
1660        form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True)
1661        self.assertTrue(form.is_valid())
1662
1663    def test_extracting_hidden_and_visible(self):
1664        class SongForm(Form):
1665            token = CharField(widget=HiddenInput)
1666            artist = CharField()
1667            name = CharField()
1668
1669        form = SongForm()
1670        self.assertEqual([f.name for f in form.hidden_fields()], ['token'])
1671        self.assertEqual([f.name for f in form.visible_fields()], ['artist', 'name'])
1672
1673    def test_hidden_initial_gets_id(self):
1674        class MyForm(Form):
1675            field1 = CharField(max_length=50, show_hidden_initial=True)
1676
1677        self.assertEqual(MyForm().as_table(), '<tr><th><label for="id_field1">Field1:</label></th><td><input id="id_field1" type="text" name="field1" maxlength="50" /><input type="hidden" name="initial-field1" id="initial-id_field1" /></td></tr>')
1678
1679    def test_error_html_required_html_classes(self):
1680        class Person(Form):
1681            name = CharField()
1682            is_cool = NullBooleanField()
1683            email = EmailField(required=False)
1684            age = IntegerField()
1685
1686        p = Person({})
1687        p.error_css_class = 'error'
1688        p.required_css_class = 'required'
1689
1690        self.assertEqual(p.as_ul(), """<li class="required error"><ul class="errorlist"><li>This field is required.</li></ul><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></li>
1691<li class="required"><label for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool">
1692<option value="1" selected="selected">Unknown</option>
1693<option value="2">Yes</option>
1694<option value="3">No</option>
1695</select></li>
1696<li><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></li>
1697<li class="required error"><ul class="errorlist"><li>This field is required.</li></ul><label for="id_age">Age:</label> <input type="text" name="age" id="id_age" /></li>""")
1698
1699        self.assertEqual(p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul>
1700<p class="required error"><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p>
1701<p class="required"><label for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool">
1702<option value="1" selected="selected">Unknown</option>
1703<option value="2">Yes</option>
1704<option value="3">No</option>
1705</select></p>
1706<p><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></p>
1707<ul class="errorlist"><li>This field is required.</li></ul>
1708<p class="required error"><label for="id_age">Age:</label> <input type="text" name="age" id="id_age" /></p>""")
1709
1710        self.assertEqual(p.as_table(), """<tr class="required error"><th><label for="id_name">Name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="name" id="id_name" /></td></tr>
1711<tr class="required"><th><label for="id_is_cool">Is cool:</label></th><td><select name="is_cool" id="id_is_cool">
1712<option value="1" selected="selected">Unknown</option>
1713<option value="2">Yes</option>
1714<option value="3">No</option>
1715</select></td></tr>
1716<tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email" /></td></tr>
1717<tr class="required error"><th><label for="id_age">Age:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="age" id="id_age" /></td></tr>""")
1718
1719    def test_label_split_datetime_not_displayed(self):
1720        class EventForm(Form):
1721            happened_at = SplitDateTimeField(widget=widgets.SplitHiddenDateTimeWidget)
1722
1723        form = EventForm()
1724        self.assertEqual(form.as_ul(), u'<input type="hidden" name="happened_at_0" id="id_happened_at_0" /><input type="hidden" name="happened_at_1" id="id_happened_at_1" />')