From 8bafde1229fdebb48383449de9bcadde06451816 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee <russell@keith-magee.com> Date: Tue, 16 Nov 2010 13:20:56 +0000 Subject: [PATCH] Migrated forms (minus localflavor) doctests. A huge thanks to Daniel Lindsley for the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@14570 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- AUTHORS | 2 +- tests/regressiontests/forms/error_messages.py | 399 ---- tests/regressiontests/forms/forms.py | 1899 ----------------- tests/regressiontests/forms/formsets.py | 762 ------- tests/regressiontests/forms/localflavor/be.py | 8 +- .../forms/{tests.py => localflavortests.py} | 23 - tests/regressiontests/forms/media.py | 385 ---- tests/regressiontests/forms/models.py | 176 -- tests/regressiontests/forms/regressions.py | 135 -- tests/regressiontests/forms/tests/__init__.py | 15 + .../forms/tests/error_messages.py | 253 +++ .../forms/{ => tests}/extra.py | 544 +++-- .../forms/{ => tests}/fields.py | 146 +- tests/regressiontests/forms/tests/forms.py | 1709 +++++++++++++++ tests/regressiontests/forms/tests/formsets.py | 797 +++++++ .../forms/{ => tests}/input_formats.py | 0 tests/regressiontests/forms/tests/media.py | 460 ++++ tests/regressiontests/forms/tests/models.py | 161 ++ .../forms/tests/regressions.py | 122 ++ tests/regressiontests/forms/tests/util.py | 57 + .../forms/{ => tests}/validators.py | 0 tests/regressiontests/forms/tests/widgets.py | 1135 ++++++++++ tests/regressiontests/forms/util.py | 60 - tests/regressiontests/forms/widgets.py | 1398 ------------ 24 files changed, 5027 insertions(+), 5619 deletions(-) delete mode 100644 tests/regressiontests/forms/error_messages.py delete mode 100644 tests/regressiontests/forms/forms.py delete mode 100644 tests/regressiontests/forms/formsets.py rename tests/regressiontests/forms/{tests.py => localflavortests.py} (79%) delete mode 100644 tests/regressiontests/forms/media.py delete mode 100644 tests/regressiontests/forms/regressions.py create mode 100644 tests/regressiontests/forms/tests/__init__.py create mode 100644 tests/regressiontests/forms/tests/error_messages.py rename tests/regressiontests/forms/{ => tests}/extra.py (54%) rename tests/regressiontests/forms/{ => tests}/fields.py (95%) create mode 100644 tests/regressiontests/forms/tests/forms.py create mode 100644 tests/regressiontests/forms/tests/formsets.py rename tests/regressiontests/forms/{ => tests}/input_formats.py (100%) create mode 100644 tests/regressiontests/forms/tests/media.py create mode 100644 tests/regressiontests/forms/tests/models.py create mode 100644 tests/regressiontests/forms/tests/regressions.py create mode 100644 tests/regressiontests/forms/tests/util.py rename tests/regressiontests/forms/{ => tests}/validators.py (100%) create mode 100644 tests/regressiontests/forms/tests/widgets.py delete mode 100644 tests/regressiontests/forms/util.py delete mode 100644 tests/regressiontests/forms/widgets.py diff --git a/AUTHORS b/AUTHORS index bc45ce7809..ac87816465 100644 --- a/AUTHORS +++ b/AUTHORS @@ -309,7 +309,7 @@ answer newbie questions, and generally made Django that much better: limodou Philip Lindborg <philip.lindborg@gmail.com> Simon Litchfield <simon@quo.com.au> - Daniel Lindsley <polarcowz@gmail.com> + Daniel Lindsley <daniel@toastdriven.com> Trey Long <trey@ktrl.com> Laurent Luce <http://www.laurentluce.com> Martin Mahner <http://www.mahner.org/> diff --git a/tests/regressiontests/forms/error_messages.py b/tests/regressiontests/forms/error_messages.py deleted file mode 100644 index 038fa39f6b..0000000000 --- a/tests/regressiontests/forms/error_messages.py +++ /dev/null @@ -1,399 +0,0 @@ -# -*- coding: utf-8 -*- -tests = r""" ->>> from django.forms import * ->>> from django.core.files.uploadedfile import SimpleUploadedFile - -# CharField ################################################################### - ->>> e = {'required': 'REQUIRED'} ->>> e['min_length'] = 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s' ->>> e['max_length'] = 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s' ->>> f = CharField(min_length=5, max_length=10, error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('1234') -Traceback (most recent call last): -... -ValidationError: [u'LENGTH 4, MIN LENGTH 5'] ->>> f.clean('12345678901') -Traceback (most recent call last): -... -ValidationError: [u'LENGTH 11, MAX LENGTH 10'] - -# IntegerField ################################################################ - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid'] = 'INVALID' ->>> e['min_value'] = 'MIN VALUE IS %(limit_value)s' ->>> e['max_value'] = 'MAX VALUE IS %(limit_value)s' ->>> f = IntegerField(min_value=5, max_value=10, error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('abc') -Traceback (most recent call last): -... -ValidationError: [u'INVALID'] ->>> f.clean('4') -Traceback (most recent call last): -... -ValidationError: [u'MIN VALUE IS 5'] ->>> f.clean('11') -Traceback (most recent call last): -... -ValidationError: [u'MAX VALUE IS 10'] - -# FloatField ################################################################## - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid'] = 'INVALID' ->>> e['min_value'] = 'MIN VALUE IS %(limit_value)s' ->>> e['max_value'] = 'MAX VALUE IS %(limit_value)s' ->>> f = FloatField(min_value=5, max_value=10, error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('abc') -Traceback (most recent call last): -... -ValidationError: [u'INVALID'] ->>> f.clean('4') -Traceback (most recent call last): -... -ValidationError: [u'MIN VALUE IS 5'] ->>> f.clean('11') -Traceback (most recent call last): -... -ValidationError: [u'MAX VALUE IS 10'] - -# DecimalField ################################################################ - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid'] = 'INVALID' ->>> e['min_value'] = 'MIN VALUE IS %(limit_value)s' ->>> e['max_value'] = 'MAX VALUE IS %(limit_value)s' ->>> e['max_digits'] = 'MAX DIGITS IS %s' ->>> e['max_decimal_places'] = 'MAX DP IS %s' ->>> e['max_whole_digits'] = 'MAX DIGITS BEFORE DP IS %s' ->>> f = DecimalField(min_value=5, max_value=10, error_messages=e) ->>> f2 = DecimalField(max_digits=4, decimal_places=2, error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('abc') -Traceback (most recent call last): -... -ValidationError: [u'INVALID'] ->>> f.clean('4') -Traceback (most recent call last): -... -ValidationError: [u'MIN VALUE IS 5'] ->>> f.clean('11') -Traceback (most recent call last): -... -ValidationError: [u'MAX VALUE IS 10'] ->>> f2.clean('123.45') -Traceback (most recent call last): -... -ValidationError: [u'MAX DIGITS IS 4'] ->>> f2.clean('1.234') -Traceback (most recent call last): -... -ValidationError: [u'MAX DP IS 2'] ->>> f2.clean('123.4') -Traceback (most recent call last): -... -ValidationError: [u'MAX DIGITS BEFORE DP IS 2'] - -# DateField ################################################################### - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid'] = 'INVALID' ->>> f = DateField(error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('abc') -Traceback (most recent call last): -... -ValidationError: [u'INVALID'] - -# TimeField ################################################################### - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid'] = 'INVALID' ->>> f = TimeField(error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('abc') -Traceback (most recent call last): -... -ValidationError: [u'INVALID'] - -# DateTimeField ############################################################### - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid'] = 'INVALID' ->>> f = DateTimeField(error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('abc') -Traceback (most recent call last): -... -ValidationError: [u'INVALID'] - -# RegexField ################################################################## - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid'] = 'INVALID' ->>> e['min_length'] = 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s' ->>> e['max_length'] = 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s' ->>> f = RegexField(r'^\d+$', min_length=5, max_length=10, error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('abcde') -Traceback (most recent call last): -... -ValidationError: [u'INVALID'] ->>> f.clean('1234') -Traceback (most recent call last): -... -ValidationError: [u'LENGTH 4, MIN LENGTH 5'] ->>> f.clean('12345678901') -Traceback (most recent call last): -... -ValidationError: [u'LENGTH 11, MAX LENGTH 10'] - -# EmailField ################################################################## - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid'] = 'INVALID' ->>> e['min_length'] = 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s' ->>> e['max_length'] = 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s' ->>> f = EmailField(min_length=8, max_length=10, error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('abcdefgh') -Traceback (most recent call last): -... -ValidationError: [u'INVALID'] ->>> f.clean('a@b.com') -Traceback (most recent call last): -... -ValidationError: [u'LENGTH 7, MIN LENGTH 8'] ->>> f.clean('aye@bee.com') -Traceback (most recent call last): -... -ValidationError: [u'LENGTH 11, MAX LENGTH 10'] - -# FileField ################################################################## - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid'] = 'INVALID' ->>> e['missing'] = 'MISSING' ->>> e['empty'] = 'EMPTY FILE' ->>> f = FileField(error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('abc') -Traceback (most recent call last): -... -ValidationError: [u'INVALID'] ->>> f.clean(SimpleUploadedFile('name', None)) -Traceback (most recent call last): -... -ValidationError: [u'EMPTY FILE'] ->>> f.clean(SimpleUploadedFile('name', '')) -Traceback (most recent call last): -... -ValidationError: [u'EMPTY FILE'] - -# URLField ################################################################## - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid'] = 'INVALID' ->>> e['invalid_link'] = 'INVALID LINK' ->>> f = URLField(verify_exists=True, error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('abc.c') -Traceback (most recent call last): -... -ValidationError: [u'INVALID'] ->>> f.clean('http://www.broken.djangoproject.com') -Traceback (most recent call last): -... -ValidationError: [u'INVALID LINK'] - -# BooleanField ################################################################ - ->>> e = {'required': 'REQUIRED'} ->>> f = BooleanField(error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] - -# ChoiceField ################################################################# - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid_choice'] = '%(value)s IS INVALID CHOICE' ->>> f = ChoiceField(choices=[('a', 'aye')], error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('b') -Traceback (most recent call last): -... -ValidationError: [u'b IS INVALID CHOICE'] - -# MultipleChoiceField ######################################################### - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid_choice'] = '%(value)s IS INVALID CHOICE' ->>> e['invalid_list'] = 'NOT A LIST' ->>> f = MultipleChoiceField(choices=[('a', 'aye')], error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('b') -Traceback (most recent call last): -... -ValidationError: [u'NOT A LIST'] ->>> f.clean(['b']) -Traceback (most recent call last): -... -ValidationError: [u'b IS INVALID CHOICE'] - -# SplitDateTimeField ########################################################## - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid_date'] = 'INVALID DATE' ->>> e['invalid_time'] = 'INVALID TIME' ->>> f = SplitDateTimeField(error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean(['a', 'b']) -Traceback (most recent call last): -... -ValidationError: [u'INVALID DATE', u'INVALID TIME'] - -# IPAddressField ############################################################## - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid'] = 'INVALID IP ADDRESS' ->>> f = IPAddressField(error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('127.0.0') -Traceback (most recent call last): -... -ValidationError: [u'INVALID IP ADDRESS'] - -############################################################################### - -# Create choices for the model choice field tests below. - ->>> from regressiontests.forms.models import ChoiceModel ->>> ChoiceModel.objects.create(pk=1, name='a') -<ChoiceModel: ChoiceModel object> ->>> ChoiceModel.objects.create(pk=2, name='b') -<ChoiceModel: ChoiceModel object> ->>> ChoiceModel.objects.create(pk=3, name='c') -<ChoiceModel: ChoiceModel object> - -# ModelChoiceField ############################################################ - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid_choice'] = 'INVALID CHOICE' ->>> f = ModelChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('4') -Traceback (most recent call last): -... -ValidationError: [u'INVALID CHOICE'] - -# ModelMultipleChoiceField #################################################### - ->>> e = {'required': 'REQUIRED'} ->>> e['invalid_choice'] = '%s IS INVALID CHOICE' ->>> e['list'] = 'NOT A LIST OF VALUES' ->>> f = ModelMultipleChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'REQUIRED'] ->>> f.clean('3') -Traceback (most recent call last): -... -ValidationError: [u'NOT A LIST OF VALUES'] ->>> f.clean(['4']) -Traceback (most recent call last): -... -ValidationError: [u'4 IS INVALID CHOICE'] - -# Subclassing ErrorList ####################################################### - ->>> from django.utils.safestring import mark_safe ->>> ->>> class TestForm(Form): -... first_name = CharField() -... last_name = CharField() -... birthday = DateField() -... -... def clean(self): -... raise ValidationError("I like to be awkward.") -... ->>> class CustomErrorList(util.ErrorList): -... def __unicode__(self): -... return self.as_divs() -... def as_divs(self): -... if not self: return u'' -... return mark_safe(u'<div class="error">%s</div>' -... % ''.join([u'<p>%s</p>' % e for e in self])) -... - -This form should print errors the default way. - ->>> form1 = TestForm({'first_name': 'John'}) ->>> print form1['last_name'].errors -<ul class="errorlist"><li>This field is required.</li></ul> ->>> print form1.errors['__all__'] -<ul class="errorlist"><li>I like to be awkward.</li></ul> - -This one should wrap error groups in the customized way. - ->>> form2 = TestForm({'first_name': 'John'}, error_class=CustomErrorList) ->>> print form2['last_name'].errors -<div class="error"><p>This field is required.</p></div> ->>> print form2.errors['__all__'] -<div class="error"><p>I like to be awkward.</p></div> - -""" diff --git a/tests/regressiontests/forms/forms.py b/tests/regressiontests/forms/forms.py deleted file mode 100644 index 91594139f2..0000000000 --- a/tests/regressiontests/forms/forms.py +++ /dev/null @@ -1,1899 +0,0 @@ -# -*- coding: utf-8 -*- -tests = r""" ->>> from django.forms import * ->>> from django.core.files.uploadedfile import SimpleUploadedFile ->>> import datetime ->>> import time ->>> import re ->>> from decimal import Decimal - -######### -# Forms # -######### - -A Form is a collection of Fields. It knows how to validate a set of data and it -knows how to render itself in a couple of default ways (e.g., an HTML table). -You can pass it data in __init__(), as a dictionary. - -# Form ######################################################################## - ->>> class Person(Form): -... first_name = CharField() -... last_name = CharField() -... birthday = DateField() - -Pass a dictionary to a Form's __init__(). ->>> p = Person({'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9'}) ->>> p.is_bound -True ->>> p.errors -{} ->>> p.is_valid() -True ->>> p.errors.as_ul() -u'' ->>> p.errors.as_text() -u'' ->>> p.cleaned_data["first_name"], p.cleaned_data["last_name"], p.cleaned_data["birthday"] -(u'John', u'Lennon', datetime.date(1940, 10, 9)) ->>> print p['first_name'] -<input type="text" name="first_name" value="John" id="id_first_name" /> ->>> print p['last_name'] -<input type="text" name="last_name" value="Lennon" id="id_last_name" /> ->>> print p['birthday'] -<input type="text" name="birthday" value="1940-10-9" id="id_birthday" /> ->>> print p['nonexistentfield'] -Traceback (most recent call last): -... -KeyError: "Key 'nonexistentfield' not found in Form" - ->>> for boundfield in p: -... print boundfield -<input type="text" name="first_name" value="John" id="id_first_name" /> -<input type="text" name="last_name" value="Lennon" id="id_last_name" /> -<input type="text" name="birthday" value="1940-10-9" id="id_birthday" /> ->>> for boundfield in p: -... print boundfield.label, boundfield.data -First name John -Last name Lennon -Birthday 1940-10-9 ->>> print p -<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr> -<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="Lennon" id="id_last_name" /></td></tr> -<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr> - -Empty dictionaries are valid, too. ->>> p = Person({}) ->>> p.is_bound -True ->>> p.errors['first_name'] -[u'This field is required.'] ->>> p.errors['last_name'] -[u'This field is required.'] ->>> p.errors['birthday'] -[u'This field is required.'] ->>> p.is_valid() -False ->>> p.cleaned_data -Traceback (most recent call last): -... -AttributeError: 'Person' object has no attribute 'cleaned_data' ->>> print p -<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" id="id_first_name" /></td></tr> -<tr><th><label for="id_last_name">Last name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="last_name" id="id_last_name" /></td></tr> -<tr><th><label for="id_birthday">Birthday:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="birthday" id="id_birthday" /></td></tr> ->>> print p.as_table() -<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" id="id_first_name" /></td></tr> -<tr><th><label for="id_last_name">Last name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="last_name" id="id_last_name" /></td></tr> -<tr><th><label for="id_birthday">Birthday:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="birthday" id="id_birthday" /></td></tr> ->>> print p.as_ul() -<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li> -<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li> -<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li> ->>> print p.as_p() -<ul class="errorlist"><li>This field is required.</li></ul> -<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p> -<ul class="errorlist"><li>This field is required.</li></ul> -<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p> -<ul class="errorlist"><li>This field is required.</li></ul> -<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p> - -If you don't pass any values to the Form's __init__(), or if you pass None, -the Form will be considered unbound and won't do any validation. Form.errors -will be an empty dictionary *but* Form.is_valid() will return False. ->>> p = Person() ->>> p.is_bound -False ->>> p.errors -{} ->>> p.is_valid() -False ->>> p.cleaned_data -Traceback (most recent call last): -... -AttributeError: 'Person' object has no attribute 'cleaned_data' ->>> print p -<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr> -<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr> -<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr> ->>> print p.as_table() -<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr> -<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr> -<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr> ->>> print p.as_ul() -<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li> -<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li> -<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li> ->>> print p.as_p() -<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p> -<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p> -<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p> - -Unicode values are handled properly. ->>> p = Person({'first_name': u'John', 'last_name': u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'}) ->>> 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>' ->>> 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>' ->>> p.as_p() -u'<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></p>\n<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></p>\n<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></p>' - ->>> p = Person({'last_name': u'Lennon'}) ->>> p.errors['first_name'] -[u'This field is required.'] ->>> p.errors['birthday'] -[u'This field is required.'] ->>> p.is_valid() -False ->>> 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>' ->>> print p.errors.as_text() -* first_name - * This field is required. -* birthday - * This field is required. ->>> p.cleaned_data -Traceback (most recent call last): -... -AttributeError: 'Person' object has no attribute 'cleaned_data' ->>> p['first_name'].errors -[u'This field is required.'] ->>> p['first_name'].errors.as_ul() -u'<ul class="errorlist"><li>This field is required.</li></ul>' ->>> p['first_name'].errors.as_text() -u'* This field is required.' - ->>> p = Person() ->>> print p['first_name'] -<input type="text" name="first_name" id="id_first_name" /> ->>> print p['last_name'] -<input type="text" name="last_name" id="id_last_name" /> ->>> print p['birthday'] -<input type="text" name="birthday" id="id_birthday" /> - -cleaned_data will always *only* contain a key for fields defined in the -Form, even if you pass extra data when you define the Form. In this -example, we pass a bunch of extra fields to the form constructor, -but cleaned_data contains only the form's fields. ->>> data = {'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9', 'extra1': 'hello', 'extra2': 'hello'} ->>> p = Person(data) ->>> p.is_valid() -True ->>> p.cleaned_data['first_name'] -u'John' ->>> p.cleaned_data['last_name'] -u'Lennon' ->>> p.cleaned_data['birthday'] -datetime.date(1940, 10, 9) - - -cleaned_data will include a key and value for *all* fields defined in the Form, -even if the Form's data didn't include a value for fields that are not -required. In this example, the data dictionary doesn't include a value for the -"nick_name" field, but cleaned_data includes it. For CharFields, it's set to the -empty string. ->>> class OptionalPersonForm(Form): -... first_name = CharField() -... last_name = CharField() -... nick_name = CharField(required=False) ->>> data = {'first_name': u'John', 'last_name': u'Lennon'} ->>> f = OptionalPersonForm(data) ->>> f.is_valid() -True ->>> f.cleaned_data['nick_name'] -u'' ->>> f.cleaned_data['first_name'] -u'John' ->>> f.cleaned_data['last_name'] -u'Lennon' - -For DateFields, it's set to None. ->>> class OptionalPersonForm(Form): -... first_name = CharField() -... last_name = CharField() -... birth_date = DateField(required=False) ->>> data = {'first_name': u'John', 'last_name': u'Lennon'} ->>> f = OptionalPersonForm(data) ->>> f.is_valid() -True ->>> print f.cleaned_data['birth_date'] -None ->>> f.cleaned_data['first_name'] -u'John' ->>> f.cleaned_data['last_name'] -u'Lennon' - -"auto_id" tells the Form to add an "id" attribute to each form element. -If it's a string that contains '%s', Django will use that as a format string -into which the field's name will be inserted. It will also put a <label> around -the human-readable labels for a field. ->>> p = Person(auto_id='%s_id') ->>> print p.as_table() -<tr><th><label for="first_name_id">First name:</label></th><td><input type="text" name="first_name" id="first_name_id" /></td></tr> -<tr><th><label for="last_name_id">Last name:</label></th><td><input type="text" name="last_name" id="last_name_id" /></td></tr> -<tr><th><label for="birthday_id">Birthday:</label></th><td><input type="text" name="birthday" id="birthday_id" /></td></tr> ->>> print p.as_ul() -<li><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" /></li> -<li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></li> -<li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></li> ->>> print p.as_p() -<p><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" /></p> -<p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></p> -<p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></p> - -If auto_id is any True value whose str() does not contain '%s', the "id" -attribute will be the name of the field. ->>> p = Person(auto_id=True) ->>> print p.as_ul() -<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" /></li> -<li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li> -<li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li> - -If auto_id is any False value, an "id" attribute won't be output unless it -was manually entered. ->>> p = Person(auto_id=False) ->>> print p.as_ul() -<li>First name: <input type="text" name="first_name" /></li> -<li>Last name: <input type="text" name="last_name" /></li> -<li>Birthday: <input type="text" name="birthday" /></li> - -In this example, auto_id is False, but the "id" attribute for the "first_name" -field is given. Also note that field gets a <label>, while the others don't. ->>> class PersonNew(Form): -... first_name = CharField(widget=TextInput(attrs={'id': 'first_name_id'})) -... last_name = CharField() -... birthday = DateField() ->>> p = PersonNew(auto_id=False) ->>> print p.as_ul() -<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" /></li> -<li>Last name: <input type="text" name="last_name" /></li> -<li>Birthday: <input type="text" name="birthday" /></li> - -If the "id" attribute is specified in the Form and auto_id is True, the "id" -attribute in the Form gets precedence. ->>> p = PersonNew(auto_id=True) ->>> print p.as_ul() -<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" /></li> -<li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li> -<li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li> - ->>> class SignupForm(Form): -... email = EmailField() -... get_spam = BooleanField() ->>> f = SignupForm(auto_id=False) ->>> print f['email'] -<input type="text" name="email" /> ->>> print f['get_spam'] -<input type="checkbox" name="get_spam" /> - ->>> f = SignupForm({'email': 'test@example.com', 'get_spam': True}, auto_id=False) ->>> print f['email'] -<input type="text" name="email" value="test@example.com" /> ->>> print f['get_spam'] -<input checked="checked" type="checkbox" name="get_spam" /> - -'True' or 'true' should be rendered without a value attribute ->>> f = SignupForm({'email': 'test@example.com', 'get_spam': 'True'}, auto_id=False) ->>> print f['get_spam'] -<input checked="checked" type="checkbox" name="get_spam" /> - ->>> f = SignupForm({'email': 'test@example.com', 'get_spam': 'true'}, auto_id=False) ->>> print f['get_spam'] -<input checked="checked" type="checkbox" name="get_spam" /> - -A value of 'False' or 'false' should be rendered unchecked ->>> f = SignupForm({'email': 'test@example.com', 'get_spam': 'False'}, auto_id=False) ->>> print f['get_spam'] -<input type="checkbox" name="get_spam" /> - ->>> f = SignupForm({'email': 'test@example.com', 'get_spam': 'false'}, auto_id=False) ->>> print f['get_spam'] -<input type="checkbox" name="get_spam" /> - -Any Field can have a Widget class passed to its constructor: ->>> class ContactForm(Form): -... subject = CharField() -... message = CharField(widget=Textarea) ->>> f = ContactForm(auto_id=False) ->>> print f['subject'] -<input type="text" name="subject" /> ->>> print f['message'] -<textarea rows="10" cols="40" name="message"></textarea> - -as_textarea(), as_text() and as_hidden() are shortcuts for changing the output -widget type: ->>> f['subject'].as_textarea() -u'<textarea rows="10" cols="40" name="subject"></textarea>' ->>> f['message'].as_text() -u'<input type="text" name="message" />' ->>> f['message'].as_hidden() -u'<input type="hidden" name="message" />' - -The 'widget' parameter to a Field can also be an instance: ->>> class ContactForm(Form): -... subject = CharField() -... message = CharField(widget=Textarea(attrs={'rows': 80, 'cols': 20})) ->>> f = ContactForm(auto_id=False) ->>> print f['message'] -<textarea rows="80" cols="20" name="message"></textarea> - -Instance-level attrs are *not* carried over to as_textarea(), as_text() and -as_hidden(): ->>> f['message'].as_text() -u'<input type="text" name="message" />' ->>> f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False) ->>> f['subject'].as_textarea() -u'<textarea rows="10" cols="40" name="subject">Hello</textarea>' ->>> f['message'].as_text() -u'<input type="text" name="message" value="I love you." />' ->>> f['message'].as_hidden() -u'<input type="hidden" name="message" value="I love you." />' - -For a form with a <select>, use ChoiceField: ->>> class FrameworkForm(Form): -... name = CharField() -... language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')]) ->>> f = FrameworkForm(auto_id=False) ->>> print f['language'] -<select name="language"> -<option value="P">Python</option> -<option value="J">Java</option> -</select> ->>> f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) ->>> print f['language'] -<select name="language"> -<option value="P" selected="selected">Python</option> -<option value="J">Java</option> -</select> - -A subtlety: If one of the choices' value is the empty string and the form is -unbound, then the <option> for the empty-string choice will get selected="selected". ->>> class FrameworkForm(Form): -... name = CharField() -... language = ChoiceField(choices=[('', '------'), ('P', 'Python'), ('J', 'Java')]) ->>> f = FrameworkForm(auto_id=False) ->>> print f['language'] -<select name="language"> -<option value="" selected="selected">------</option> -<option value="P">Python</option> -<option value="J">Java</option> -</select> - -You can specify widget attributes in the Widget constructor. ->>> class FrameworkForm(Form): -... name = CharField() -... language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(attrs={'class': 'foo'})) ->>> f = FrameworkForm(auto_id=False) ->>> print f['language'] -<select class="foo" name="language"> -<option value="P">Python</option> -<option value="J">Java</option> -</select> ->>> f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) ->>> print f['language'] -<select class="foo" name="language"> -<option value="P" selected="selected">Python</option> -<option value="J">Java</option> -</select> - -When passing a custom widget instance to ChoiceField, note that setting -'choices' on the widget is meaningless. The widget will use the choices -defined on the Field, not the ones defined on the Widget. ->>> class FrameworkForm(Form): -... name = CharField() -... language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'})) ->>> f = FrameworkForm(auto_id=False) ->>> print f['language'] -<select class="foo" name="language"> -<option value="P">Python</option> -<option value="J">Java</option> -</select> ->>> f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) ->>> print f['language'] -<select class="foo" name="language"> -<option value="P" selected="selected">Python</option> -<option value="J">Java</option> -</select> - -You can set a ChoiceField's choices after the fact. ->>> class FrameworkForm(Form): -... name = CharField() -... language = ChoiceField() ->>> f = FrameworkForm(auto_id=False) ->>> print f['language'] -<select name="language"> -</select> ->>> f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')] ->>> print f['language'] -<select name="language"> -<option value="P">Python</option> -<option value="J">Java</option> -</select> - -Add widget=RadioSelect to use that widget with a ChoiceField. ->>> class FrameworkForm(Form): -... name = CharField() -... language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=RadioSelect) ->>> f = FrameworkForm(auto_id=False) ->>> print f['language'] -<ul> -<li><label><input type="radio" name="language" value="P" /> Python</label></li> -<li><label><input type="radio" name="language" value="J" /> Java</label></li> -</ul> ->>> print f -<tr><th>Name:</th><td><input type="text" name="name" /></td></tr> -<tr><th>Language:</th><td><ul> -<li><label><input type="radio" name="language" value="P" /> Python</label></li> -<li><label><input type="radio" name="language" value="J" /> Java</label></li> -</ul></td></tr> ->>> print f.as_ul() -<li>Name: <input type="text" name="name" /></li> -<li>Language: <ul> -<li><label><input type="radio" name="language" value="P" /> Python</label></li> -<li><label><input type="radio" name="language" value="J" /> Java</label></li> -</ul></li> - -Regarding auto_id and <label>, RadioSelect is a special case. Each radio button -gets a distinct ID, formed by appending an underscore plus the button's -zero-based index. ->>> f = FrameworkForm(auto_id='id_%s') ->>> print f['language'] -<ul> -<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li> -<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li> -</ul> - -When RadioSelect is used with auto_id, and the whole form is printed using -either as_table() or as_ul(), the label for the RadioSelect will point to the -ID of the *first* radio button. ->>> print f -<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" id="id_name" /></td></tr> -<tr><th><label for="id_language_0">Language:</label></th><td><ul> -<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li> -<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li> -</ul></td></tr> ->>> print f.as_ul() -<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></li> -<li><label for="id_language_0">Language:</label> <ul> -<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li> -<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li> -</ul></li> ->>> print f.as_p() -<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p> -<p><label for="id_language_0">Language:</label> <ul> -<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li> -<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li> -</ul></p> - -MultipleChoiceField is a special case, as its data is required to be a list: ->>> class SongForm(Form): -... name = CharField() -... composers = MultipleChoiceField() ->>> f = SongForm(auto_id=False) ->>> print f['composers'] -<select multiple="multiple" name="composers"> -</select> ->>> class SongForm(Form): -... name = CharField() -... composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')]) ->>> f = SongForm(auto_id=False) ->>> print f['composers'] -<select multiple="multiple" name="composers"> -<option value="J">John Lennon</option> -<option value="P">Paul McCartney</option> -</select> ->>> f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False) ->>> print f['name'] -<input type="text" name="name" value="Yesterday" /> ->>> print f['composers'] -<select multiple="multiple" name="composers"> -<option value="J">John Lennon</option> -<option value="P" selected="selected">Paul McCartney</option> -</select> - -MultipleChoiceField rendered as_hidden() is a special case. Because it can -have multiple values, its as_hidden() renders multiple <input type="hidden"> -tags. ->>> f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False) ->>> print f['composers'].as_hidden() -<input type="hidden" name="composers" value="P" /> ->>> f = SongForm({'name': 'From Me To You', 'composers': ['P', 'J']}, auto_id=False) ->>> print f['composers'].as_hidden() -<input type="hidden" name="composers" value="P" /> -<input type="hidden" name="composers" value="J" /> - -DateTimeField rendered as_hidden() is special too - ->>> class MessageForm(Form): -... when = SplitDateTimeField() ->>> f = MessageForm({'when_0': '1992-01-01', 'when_1': '01:01'}) ->>> print f.is_valid() -True ->>> print 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" /> ->>> print 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" /> - -MultipleChoiceField can also be used with the CheckboxSelectMultiple widget. ->>> class SongForm(Form): -... name = CharField() -... composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple) ->>> f = SongForm(auto_id=False) ->>> print f['composers'] -<ul> -<li><label><input type="checkbox" name="composers" value="J" /> John Lennon</label></li> -<li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li> -</ul> ->>> f = SongForm({'composers': ['J']}, auto_id=False) ->>> print f['composers'] -<ul> -<li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li> -<li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li> -</ul> ->>> f = SongForm({'composers': ['J', 'P']}, auto_id=False) ->>> print f['composers'] -<ul> -<li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li> -<li><label><input checked="checked" type="checkbox" name="composers" value="P" /> Paul McCartney</label></li> -</ul> - -Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox -gets a distinct ID, formed by appending an underscore plus the checkbox's -zero-based index. ->>> f = SongForm(auto_id='%s_id') ->>> print f['composers'] -<ul> -<li><label for="composers_id_0"><input type="checkbox" name="composers" value="J" id="composers_id_0" /> John Lennon</label></li> -<li><label for="composers_id_1"><input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li> -</ul> - -Data for a MultipleChoiceField should be a list. QueryDict, MultiValueDict and -MergeDict (when created as a merge of MultiValueDicts) conveniently work with -this. ->>> data = {'name': 'Yesterday', 'composers': ['J', 'P']} ->>> f = SongForm(data) ->>> f.errors -{} ->>> from django.http import QueryDict ->>> data = QueryDict('name=Yesterday&composers=J&composers=P') ->>> f = SongForm(data) ->>> f.errors -{} ->>> from django.utils.datastructures import MultiValueDict ->>> data = MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])) ->>> f = SongForm(data) ->>> f.errors -{} ->>> from django.utils.datastructures import MergeDict ->>> data = MergeDict(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P']))) ->>> f = SongForm(data) ->>> f.errors -{} - -The MultipleHiddenInput widget renders multiple values as hidden fields. ->>> class SongFormHidden(Form): -... name = CharField() -... composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=MultipleHiddenInput) ->>> f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False) ->>> print f.as_ul() -<li>Name: <input type="text" name="name" value="Yesterday" /><input type="hidden" name="composers" value="J" /> -<input type="hidden" name="composers" value="P" /></li> - -When using CheckboxSelectMultiple, the framework expects a list of input and -returns a list of input. ->>> f = SongForm({'name': 'Yesterday'}, auto_id=False) ->>> f.errors['composers'] -[u'This field is required.'] ->>> f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False) ->>> f.errors -{} ->>> f.cleaned_data['composers'] -[u'J'] ->>> f.cleaned_data['name'] -u'Yesterday' ->>> f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False) ->>> f.errors -{} ->>> f.cleaned_data['composers'] -[u'J', u'P'] ->>> f.cleaned_data['name'] -u'Yesterday' - -Validation errors are HTML-escaped when output as HTML. ->>> from django.utils.safestring import mark_safe ->>> class EscapingForm(Form): -... special_name = CharField(label="<em>Special</em> Field") -... special_safe_name = CharField(label=mark_safe("<em>Special</em> Field")) -... def clean_special_name(self): -... raise ValidationError("Something's wrong with '%s'" % self.cleaned_data['special_name']) -... def clean_special_safe_name(self): -... raise ValidationError(mark_safe("'<b>%s</b>' is a safe string" % self.cleaned_data['special_safe_name'])) - ->>> f = EscapingForm({'special_name': "Nothing to escape", 'special_safe_name': "Nothing to escape"}, auto_id=False) ->>> print f -<tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>Something's wrong with 'Nothing to escape'</li></ul><input type="text" name="special_name" value="Nothing to escape" /></td></tr> -<tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>'<b>Nothing to escape</b>' is a safe string</li></ul><input type="text" name="special_safe_name" value="Nothing to escape" /></td></tr> ->>> f = EscapingForm( -... {'special_name': "Should escape < & > and <script>alert('xss')</script>", -... 'special_safe_name': "<i>Do not escape</i>"}, auto_id=False) ->>> print f -<tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>Something's wrong with 'Should escape < & > and <script>alert('xss')</script>'</li></ul><input type="text" name="special_name" value="Should escape < & > and <script>alert('xss')</script>" /></td></tr> -<tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>'<b><i>Do not escape</i></b>' is a safe string</li></ul><input type="text" name="special_safe_name" value="<i>Do not escape</i>" /></td></tr> - -""" + \ -r""" # [This concatenation is to keep the string below the jython's 32K limit]. -# Validating multiple fields in relation to another ########################### - -There are a couple of ways to do multiple-field validation. If you want the -validation message to be associated with a particular field, implement the -clean_XXX() method on the Form, where XXX is the field name. As in -Field.clean(), the clean_XXX() method should return the cleaned value. In the -clean_XXX() method, you have access to self.cleaned_data, which is a dictionary -of all the data that has been cleaned *so far*, in order by the fields, -including the current field (e.g., the field XXX if you're in clean_XXX()). ->>> class UserRegistration(Form): -... username = CharField(max_length=10) -... password1 = CharField(widget=PasswordInput) -... password2 = CharField(widget=PasswordInput) -... def clean_password2(self): -... if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: -... raise ValidationError(u'Please make sure your passwords match.') -... return self.cleaned_data['password2'] ->>> f = UserRegistration(auto_id=False) ->>> f.errors -{} ->>> f = UserRegistration({}, auto_id=False) ->>> f.errors['username'] -[u'This field is required.'] ->>> f.errors['password1'] -[u'This field is required.'] ->>> f.errors['password2'] -[u'This field is required.'] ->>> f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) ->>> f.errors['password2'] -[u'Please make sure your passwords match.'] ->>> f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False) ->>> f.errors -{} ->>> f.cleaned_data['username'] -u'adrian' ->>> f.cleaned_data['password1'] -u'foo' ->>> f.cleaned_data['password2'] -u'foo' - -Another way of doing multiple-field validation is by implementing the -Form's clean() method. If you do this, any ValidationError raised by that -method will not be associated with a particular field; it will have a -special-case association with the field named '__all__'. -Note that in Form.clean(), you have access to self.cleaned_data, a dictionary of -all the fields/values that have *not* raised a ValidationError. Also note -Form.clean() is required to return a dictionary of all clean data. ->>> class UserRegistration(Form): -... username = CharField(max_length=10) -... password1 = CharField(widget=PasswordInput) -... password2 = CharField(widget=PasswordInput) -... def clean(self): -... if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: -... raise ValidationError(u'Please make sure your passwords match.') -... return self.cleaned_data ->>> f = UserRegistration(auto_id=False) ->>> f.errors -{} ->>> f = UserRegistration({}, auto_id=False) ->>> print f.as_table() -<tr><th>Username:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="username" maxlength="10" /></td></tr> -<tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password1" /></td></tr> -<tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password2" /></td></tr> ->>> f.errors['username'] -[u'This field is required.'] ->>> f.errors['password1'] -[u'This field is required.'] ->>> f.errors['password2'] -[u'This field is required.'] ->>> f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) ->>> f.errors['__all__'] -[u'Please make sure your passwords match.'] ->>> print f.as_table() -<tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr> -<tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" /></td></tr> -<tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr> -<tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr> ->>> print f.as_ul() -<li><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></li> -<li>Username: <input type="text" name="username" value="adrian" maxlength="10" /></li> -<li>Password1: <input type="password" name="password1" /></li> -<li>Password2: <input type="password" name="password2" /></li> ->>> f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False) ->>> f.errors -{} ->>> f.cleaned_data['username'] -u'adrian' ->>> f.cleaned_data['password1'] -u'foo' ->>> f.cleaned_data['password2'] -u'foo' - -# Dynamic construction ######################################################## - -It's possible to construct a Form dynamically by adding to the self.fields -dictionary in __init__(). Don't forget to call Form.__init__() within the -subclass' __init__(). ->>> class Person(Form): -... first_name = CharField() -... last_name = CharField() -... def __init__(self, *args, **kwargs): -... super(Person, self).__init__(*args, **kwargs) -... self.fields['birthday'] = DateField() ->>> p = Person(auto_id=False) ->>> print p -<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr> -<tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr> -<tr><th>Birthday:</th><td><input type="text" name="birthday" /></td></tr> - -Instances of a dynamic Form do not persist fields from one Form instance to -the next. ->>> class MyForm(Form): -... def __init__(self, data=None, auto_id=False, field_list=[]): -... Form.__init__(self, data, auto_id=auto_id) -... for field in field_list: -... self.fields[field[0]] = field[1] ->>> field_list = [('field1', CharField()), ('field2', CharField())] ->>> my_form = MyForm(field_list=field_list) ->>> print my_form -<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr> -<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr> ->>> field_list = [('field3', CharField()), ('field4', CharField())] ->>> my_form = MyForm(field_list=field_list) ->>> print my_form -<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr> -<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr> - ->>> class MyForm(Form): -... default_field_1 = CharField() -... default_field_2 = CharField() -... def __init__(self, data=None, auto_id=False, field_list=[]): -... Form.__init__(self, data, auto_id=auto_id) -... for field in field_list: -... self.fields[field[0]] = field[1] ->>> field_list = [('field1', CharField()), ('field2', CharField())] ->>> my_form = MyForm(field_list=field_list) ->>> print my_form -<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr> -<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr> -<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr> -<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr> ->>> field_list = [('field3', CharField()), ('field4', CharField())] ->>> my_form = MyForm(field_list=field_list) ->>> print my_form -<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr> -<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr> -<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr> -<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr> - -Similarly, changes to field attributes do not persist from one Form instance -to the next. ->>> class Person(Form): -... first_name = CharField(required=False) -... last_name = CharField(required=False) -... def __init__(self, names_required=False, *args, **kwargs): -... super(Person, self).__init__(*args, **kwargs) -... if names_required: -... self.fields['first_name'].required = True -... self.fields['first_name'].widget.attrs['class'] = 'required' -... self.fields['last_name'].required = True -... self.fields['last_name'].widget.attrs['class'] = 'required' ->>> f = Person(names_required=False) ->>> f['first_name'].field.required, f['last_name'].field.required -(False, False) ->>> f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs -({}, {}) ->>> f = Person(names_required=True) ->>> f['first_name'].field.required, f['last_name'].field.required -(True, True) ->>> f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs -({'class': 'required'}, {'class': 'required'}) ->>> f = Person(names_required=False) ->>> f['first_name'].field.required, f['last_name'].field.required -(False, False) ->>> f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs -({}, {}) ->>> class Person(Form): -... first_name = CharField(max_length=30) -... last_name = CharField(max_length=30) -... def __init__(self, name_max_length=None, *args, **kwargs): -... super(Person, self).__init__(*args, **kwargs) -... if name_max_length: -... self.fields['first_name'].max_length = name_max_length -... self.fields['last_name'].max_length = name_max_length ->>> f = Person(name_max_length=None) ->>> f['first_name'].field.max_length, f['last_name'].field.max_length -(30, 30) ->>> f = Person(name_max_length=20) ->>> f['first_name'].field.max_length, f['last_name'].field.max_length -(20, 20) ->>> f = Person(name_max_length=None) ->>> f['first_name'].field.max_length, f['last_name'].field.max_length -(30, 30) - -HiddenInput widgets are displayed differently in the as_table(), as_ul() -and as_p() output of a Form -- their verbose names are not displayed, and a -separate row is not displayed. They're displayed in the last row of the -form, directly after that row's form element. ->>> class Person(Form): -... first_name = CharField() -... last_name = CharField() -... hidden_text = CharField(widget=HiddenInput) -... birthday = DateField() ->>> p = Person(auto_id=False) ->>> print p -<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr> -<tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr> -<tr><th>Birthday:</th><td><input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></td></tr> ->>> print p.as_ul() -<li>First name: <input type="text" name="first_name" /></li> -<li>Last name: <input type="text" name="last_name" /></li> -<li>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></li> ->>> print p.as_p() -<p>First name: <input type="text" name="first_name" /></p> -<p>Last name: <input type="text" name="last_name" /></p> -<p>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></p> - -With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label. ->>> p = Person(auto_id='id_%s') ->>> print p -<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr> -<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr> -<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></td></tr> ->>> print p.as_ul() -<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li> -<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li> -<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></li> ->>> print p.as_p() -<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p> -<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p> -<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></p> - -If a field with a HiddenInput has errors, the as_table() and as_ul() output -will include the error message(s) with the text "(Hidden field [fieldname]) " -prepended. This message is displayed at the top of the output, regardless of -its field's order in the form. ->>> p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False) ->>> print p -<tr><td colspan="2"><ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul></td></tr> -<tr><th>First name:</th><td><input type="text" name="first_name" value="John" /></td></tr> -<tr><th>Last name:</th><td><input type="text" name="last_name" value="Lennon" /></td></tr> -<tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></td></tr> ->>> print p.as_ul() -<li><ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul></li> -<li>First name: <input type="text" name="first_name" value="John" /></li> -<li>Last name: <input type="text" name="last_name" value="Lennon" /></li> -<li>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></li> ->>> print p.as_p() -<ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul> -<p>First name: <input type="text" name="first_name" value="John" /></p> -<p>Last name: <input type="text" name="last_name" value="Lennon" /></p> -<p>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></p> - -A corner case: It's possible for a form to have only HiddenInputs. ->>> class TestForm(Form): -... foo = CharField(widget=HiddenInput) -... bar = CharField(widget=HiddenInput) ->>> p = TestForm(auto_id=False) ->>> print p.as_table() -<input type="hidden" name="foo" /><input type="hidden" name="bar" /> ->>> print p.as_ul() -<input type="hidden" name="foo" /><input type="hidden" name="bar" /> ->>> print p.as_p() -<input type="hidden" name="foo" /><input type="hidden" name="bar" /> - -A Form's fields are displayed in the same order in which they were defined. ->>> class TestForm(Form): -... field1 = CharField() -... field2 = CharField() -... field3 = CharField() -... field4 = CharField() -... field5 = CharField() -... field6 = CharField() -... field7 = CharField() -... field8 = CharField() -... field9 = CharField() -... field10 = CharField() -... field11 = CharField() -... field12 = CharField() -... field13 = CharField() -... field14 = CharField() ->>> p = TestForm(auto_id=False) ->>> print p -<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr> -<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr> -<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr> -<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr> -<tr><th>Field5:</th><td><input type="text" name="field5" /></td></tr> -<tr><th>Field6:</th><td><input type="text" name="field6" /></td></tr> -<tr><th>Field7:</th><td><input type="text" name="field7" /></td></tr> -<tr><th>Field8:</th><td><input type="text" name="field8" /></td></tr> -<tr><th>Field9:</th><td><input type="text" name="field9" /></td></tr> -<tr><th>Field10:</th><td><input type="text" name="field10" /></td></tr> -<tr><th>Field11:</th><td><input type="text" name="field11" /></td></tr> -<tr><th>Field12:</th><td><input type="text" name="field12" /></td></tr> -<tr><th>Field13:</th><td><input type="text" name="field13" /></td></tr> -<tr><th>Field14:</th><td><input type="text" name="field14" /></td></tr> - -Some Field classes have an effect on the HTML attributes of their associated -Widget. If you set max_length in a CharField and its associated widget is -either a TextInput or PasswordInput, then the widget's rendered HTML will -include the "maxlength" attribute. ->>> class UserRegistration(Form): -... username = CharField(max_length=10) # uses TextInput by default -... password = CharField(max_length=10, widget=PasswordInput) -... realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test -... address = CharField() # no max_length defined here ->>> p = UserRegistration(auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" maxlength="10" /></li> -<li>Password: <input type="password" name="password" maxlength="10" /></li> -<li>Realname: <input type="text" name="realname" maxlength="10" /></li> -<li>Address: <input type="text" name="address" /></li> - -If you specify a custom "attrs" that includes the "maxlength" attribute, -the Field's max_length attribute will override whatever "maxlength" you specify -in "attrs". ->>> class UserRegistration(Form): -... username = CharField(max_length=10, widget=TextInput(attrs={'maxlength': 20})) -... password = CharField(max_length=10, widget=PasswordInput) ->>> p = UserRegistration(auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" maxlength="10" /></li> -<li>Password: <input type="password" name="password" maxlength="10" /></li> - -# Specifying labels ########################################################### - -You can specify the label for a field by using the 'label' argument to a Field -class. If you don't specify 'label', Django will use the field name with -underscores converted to spaces, and the initial letter capitalized. ->>> class UserRegistration(Form): -... username = CharField(max_length=10, label='Your username') -... password1 = CharField(widget=PasswordInput) -... password2 = CharField(widget=PasswordInput, label='Password (again)') ->>> p = UserRegistration(auto_id=False) ->>> print p.as_ul() -<li>Your username: <input type="text" name="username" maxlength="10" /></li> -<li>Password1: <input type="password" name="password1" /></li> -<li>Password (again): <input type="password" name="password2" /></li> - -Labels for as_* methods will only end in a colon if they don't end in other -punctuation already. ->>> class Questions(Form): -... q1 = CharField(label='The first question') -... q2 = CharField(label='What is your name?') -... q3 = CharField(label='The answer to life is:') -... q4 = CharField(label='Answer this question!') -... q5 = CharField(label='The last question. Period.') ->>> print Questions(auto_id=False).as_p() -<p>The first question: <input type="text" name="q1" /></p> -<p>What is your name? <input type="text" name="q2" /></p> -<p>The answer to life is: <input type="text" name="q3" /></p> -<p>Answer this question! <input type="text" name="q4" /></p> -<p>The last question. Period. <input type="text" name="q5" /></p> ->>> print Questions().as_p() -<p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" /></p> -<p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" /></p> -<p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" /></p> -<p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" /></p> -<p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" /></p> - -A label can be a Unicode object or a bytestring with special characters. ->>> class UserRegistration(Form): -... username = CharField(max_length=10, label='ŠĐĆŽćžšđ') -... password = CharField(widget=PasswordInput, label=u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') ->>> p = UserRegistration(auto_id=False) ->>> 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>' - -If a label is set to the empty string for a field, that field won't get a label. ->>> class UserRegistration(Form): -... username = CharField(max_length=10, label='') -... password = CharField(widget=PasswordInput) ->>> p = UserRegistration(auto_id=False) ->>> print p.as_ul() -<li> <input type="text" name="username" maxlength="10" /></li> -<li>Password: <input type="password" name="password" /></li> ->>> p = UserRegistration(auto_id='id_%s') ->>> print p.as_ul() -<li> <input id="id_username" type="text" name="username" maxlength="10" /></li> -<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li> - -If label is None, Django will auto-create the label from the field name. This -is default behavior. ->>> class UserRegistration(Form): -... username = CharField(max_length=10, label=None) -... password = CharField(widget=PasswordInput) ->>> p = UserRegistration(auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" maxlength="10" /></li> -<li>Password: <input type="password" name="password" /></li> ->>> p = UserRegistration(auto_id='id_%s') ->>> print p.as_ul() -<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></li> -<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li> - - -# Label Suffix ################################################################ - -You can specify the 'label_suffix' argument to a Form class to modify the -punctuation symbol used at the end of a label. By default, the colon (:) is -used, and is only appended to the label if the label doesn't already end with a -punctuation symbol: ., !, ? or :. If you specify a different suffix, it will -be appended regardless of the last character of the label. - ->>> class FavoriteForm(Form): -... color = CharField(label='Favorite color?') -... animal = CharField(label='Favorite animal') -... ->>> f = FavoriteForm(auto_id=False) ->>> print f.as_ul() -<li>Favorite color? <input type="text" name="color" /></li> -<li>Favorite animal: <input type="text" name="animal" /></li> ->>> f = FavoriteForm(auto_id=False, label_suffix='?') ->>> print f.as_ul() -<li>Favorite color? <input type="text" name="color" /></li> -<li>Favorite animal? <input type="text" name="animal" /></li> ->>> f = FavoriteForm(auto_id=False, label_suffix='') ->>> print f.as_ul() -<li>Favorite color? <input type="text" name="color" /></li> -<li>Favorite animal <input type="text" name="animal" /></li> ->>> f = FavoriteForm(auto_id=False, label_suffix=u'\u2192') ->>> f.as_ul() -u'<li>Favorite color? <input type="text" name="color" /></li>\n<li>Favorite animal\u2192 <input type="text" name="animal" /></li>' - -""" + \ -r""" # [This concatenation is to keep the string below the jython's 32K limit]. - -# Initial data ################################################################ - -You can specify initial data for a field by using the 'initial' argument to a -Field class. This initial data is displayed when a Form is rendered with *no* -data. It is not displayed when a Form is rendered with any data (including an -empty dictionary). Also, the initial value is *not* used if data for a -particular required field isn't provided. ->>> class UserRegistration(Form): -... username = CharField(max_length=10, initial='django') -... password = CharField(widget=PasswordInput) - -Here, we're not submitting any data, so the initial value will be displayed. ->>> p = UserRegistration(auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li> -<li>Password: <input type="password" name="password" /></li> - -Here, we're submitting data, so the initial value will *not* be displayed. ->>> p = UserRegistration({}, auto_id=False) ->>> print p.as_ul() -<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li> -<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> ->>> p = UserRegistration({'username': u''}, auto_id=False) ->>> print p.as_ul() -<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li> -<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> ->>> p = UserRegistration({'username': u'foo'}, auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li> -<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> - -An 'initial' value is *not* used as a fallback if data is not provided. In this -example, we don't provide a value for 'username', and the form raises a -validation error rather than using the initial value for 'username'. ->>> p = UserRegistration({'password': 'secret'}) ->>> p.errors['username'] -[u'This field is required.'] ->>> p.is_valid() -False - -# Dynamic initial data ######################################################## - -The previous technique dealt with "hard-coded" initial data, but it's also -possible to specify initial data after you've already created the Form class -(i.e., at runtime). Use the 'initial' parameter to the Form constructor. This -should be a dictionary containing initial values for one or more fields in the -form, keyed by field name. - ->>> class UserRegistration(Form): -... username = CharField(max_length=10) -... password = CharField(widget=PasswordInput) - -Here, we're not submitting any data, so the initial value will be displayed. ->>> p = UserRegistration(initial={'username': 'django'}, auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li> -<li>Password: <input type="password" name="password" /></li> ->>> p = UserRegistration(initial={'username': 'stephane'}, auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li> -<li>Password: <input type="password" name="password" /></li> - -The 'initial' parameter is meaningless if you pass data. ->>> p = UserRegistration({}, initial={'username': 'django'}, auto_id=False) ->>> print p.as_ul() -<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li> -<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> ->>> p = UserRegistration({'username': u''}, initial={'username': 'django'}, auto_id=False) ->>> print p.as_ul() -<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li> -<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> ->>> p = UserRegistration({'username': u'foo'}, initial={'username': 'django'}, auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li> -<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> - -A dynamic 'initial' value is *not* used as a fallback if data is not provided. -In this example, we don't provide a value for 'username', and the form raises a -validation error rather than using the initial value for 'username'. ->>> p = UserRegistration({'password': 'secret'}, initial={'username': 'django'}) ->>> p.errors['username'] -[u'This field is required.'] ->>> p.is_valid() -False - -If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(), -then the latter will get precedence. ->>> class UserRegistration(Form): -... username = CharField(max_length=10, initial='django') -... password = CharField(widget=PasswordInput) ->>> p = UserRegistration(initial={'username': 'babik'}, auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" value="babik" maxlength="10" /></li> -<li>Password: <input type="password" name="password" /></li> - -# Callable initial data ######################################################## - -The previous technique dealt with raw values as initial data, but it's also -possible to specify callable data. - ->>> class UserRegistration(Form): -... username = CharField(max_length=10) -... password = CharField(widget=PasswordInput) -... options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')]) - -We need to define functions that get called later. ->>> def initial_django(): -... return 'django' ->>> def initial_stephane(): -... return 'stephane' ->>> def initial_options(): -... return ['f','b'] ->>> def initial_other_options(): -... return ['b','w'] - - -Here, we're not submitting any data, so the initial value will be displayed. ->>> p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li> -<li>Password: <input type="password" name="password" /></li> -<li>Options: <select multiple="multiple" name="options"> -<option value="f" selected="selected">foo</option> -<option value="b" selected="selected">bar</option> -<option value="w">whiz</option> -</select></li> - -The 'initial' parameter is meaningless if you pass data. ->>> p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False) ->>> print p.as_ul() -<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li> -<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> -<li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options"> -<option value="f">foo</option> -<option value="b">bar</option> -<option value="w">whiz</option> -</select></li> ->>> p = UserRegistration({'username': u''}, initial={'username': initial_django}, auto_id=False) ->>> print p.as_ul() -<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li> -<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> -<li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options"> -<option value="f">foo</option> -<option value="b">bar</option> -<option value="w">whiz</option> -</select></li> ->>> p = UserRegistration({'username': u'foo', 'options':['f','b']}, initial={'username': initial_django}, auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li> -<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> -<li>Options: <select multiple="multiple" name="options"> -<option value="f" selected="selected">foo</option> -<option value="b" selected="selected">bar</option> -<option value="w">whiz</option> -</select></li> - -A callable 'initial' value is *not* used as a fallback if data is not provided. -In this example, we don't provide a value for 'username', and the form raises a -validation error rather than using the initial value for 'username'. ->>> p = UserRegistration({'password': 'secret'}, initial={'username': initial_django, 'options': initial_options}) ->>> p.errors['username'] -[u'This field is required.'] ->>> p.is_valid() -False - -If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(), -then the latter will get precedence. ->>> class UserRegistration(Form): -... username = CharField(max_length=10, initial=initial_django) -... password = CharField(widget=PasswordInput) -... options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')], initial=initial_other_options) - ->>> p = UserRegistration(auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li> -<li>Password: <input type="password" name="password" /></li> -<li>Options: <select multiple="multiple" name="options"> -<option value="f">foo</option> -<option value="b" selected="selected">bar</option> -<option value="w" selected="selected">whiz</option> -</select></li> ->>> p = UserRegistration(initial={'username': initial_stephane, 'options': initial_options}, auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li> -<li>Password: <input type="password" name="password" /></li> -<li>Options: <select multiple="multiple" name="options"> -<option value="f" selected="selected">foo</option> -<option value="b" selected="selected">bar</option> -<option value="w">whiz</option> -</select></li> - -# Help text ################################################################### - -You can specify descriptive text for a field by using the 'help_text' argument -to a Field class. This help text is displayed when a Form is rendered. ->>> class UserRegistration(Form): -... username = CharField(max_length=10, help_text='e.g., user@example.com') -... password = CharField(widget=PasswordInput, help_text='Choose wisely.') ->>> p = UserRegistration(auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li> -<li>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></li> ->>> print p.as_p() -<p>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></p> -<p>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></p> ->>> print 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> -<tr><th>Password:</th><td><input type="password" name="password" /><br /><span class="helptext">Choose wisely.</span></td></tr> - -The help text is displayed whether or not data is provided for the form. ->>> p = UserRegistration({'username': u'foo'}, auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" value="foo" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li> -<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></li> - -help_text is not displayed for hidden fields. It can be used for documentation -purposes, though. ->>> class UserRegistration(Form): -... username = CharField(max_length=10, help_text='e.g., user@example.com') -... password = CharField(widget=PasswordInput) -... next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination') ->>> p = UserRegistration(auto_id=False) ->>> print p.as_ul() -<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li> -<li>Password: <input type="password" name="password" /><input type="hidden" name="next" value="/" /></li> - -Help text can include arbitrary Unicode characters. ->>> class UserRegistration(Form): -... username = CharField(max_length=10, help_text='ŠĐĆŽćžšđ') ->>> p = UserRegistration(auto_id=False) ->>> 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>' - -# Subclassing forms ########################################################### - -You can subclass a Form to add fields. The resulting form subclass will have -all of the fields of the parent Form, plus whichever fields you define in the -subclass. ->>> class Person(Form): -... first_name = CharField() -... last_name = CharField() -... birthday = DateField() ->>> class Musician(Person): -... instrument = CharField() ->>> p = Person(auto_id=False) ->>> print p.as_ul() -<li>First name: <input type="text" name="first_name" /></li> -<li>Last name: <input type="text" name="last_name" /></li> -<li>Birthday: <input type="text" name="birthday" /></li> ->>> m = Musician(auto_id=False) ->>> print m.as_ul() -<li>First name: <input type="text" name="first_name" /></li> -<li>Last name: <input type="text" name="last_name" /></li> -<li>Birthday: <input type="text" name="birthday" /></li> -<li>Instrument: <input type="text" name="instrument" /></li> - -Yes, you can subclass multiple forms. The fields are added in the order in -which the parent classes are listed. ->>> class Person(Form): -... first_name = CharField() -... last_name = CharField() -... birthday = DateField() ->>> class Instrument(Form): -... instrument = CharField() ->>> class Beatle(Person, Instrument): -... haircut_type = CharField() ->>> b = Beatle(auto_id=False) ->>> print b.as_ul() -<li>First name: <input type="text" name="first_name" /></li> -<li>Last name: <input type="text" name="last_name" /></li> -<li>Birthday: <input type="text" name="birthday" /></li> -<li>Instrument: <input type="text" name="instrument" /></li> -<li>Haircut type: <input type="text" name="haircut_type" /></li> - -# Forms with prefixes ######################################################### - -Sometimes it's necessary to have multiple forms display on the same HTML page, -or multiple copies of the same form. We can accomplish this with form prefixes. -Pass the keyword argument 'prefix' to the Form constructor to use this feature. -This value will be prepended to each HTML form field name. One way to think -about this is "namespaces for HTML forms". Notice that in the data argument, -each field's key has the prefix, in this case 'person1', prepended to the -actual field name. ->>> class Person(Form): -... first_name = CharField() -... last_name = CharField() -... birthday = DateField() ->>> data = { -... 'person1-first_name': u'John', -... 'person1-last_name': u'Lennon', -... 'person1-birthday': u'1940-10-9' -... } ->>> p = Person(data, prefix='person1') ->>> print 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> -<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> -<li><label for="id_person1-birthday">Birthday:</label> <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" /></li> ->>> print p['first_name'] -<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" /> ->>> print p['last_name'] -<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" /> ->>> print p['birthday'] -<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" /> ->>> p.errors -{} ->>> p.is_valid() -True ->>> p.cleaned_data['first_name'] -u'John' ->>> p.cleaned_data['last_name'] -u'Lennon' ->>> p.cleaned_data['birthday'] -datetime.date(1940, 10, 9) - -Let's try submitting some bad data to make sure form.errors and field.errors -work as expected. ->>> data = { -... 'person1-first_name': u'', -... 'person1-last_name': u'', -... 'person1-birthday': u'' -... } ->>> p = Person(data, prefix='person1') ->>> p.errors['first_name'] -[u'This field is required.'] ->>> p.errors['last_name'] -[u'This field is required.'] ->>> p.errors['birthday'] -[u'This field is required.'] ->>> p['first_name'].errors -[u'This field is required.'] ->>> p['person1-first_name'].errors -Traceback (most recent call last): -... -KeyError: "Key 'person1-first_name' not found in Form" - -In this example, the data doesn't have a prefix, but the form requires it, so -the form doesn't "see" the fields. ->>> data = { -... 'first_name': u'John', -... 'last_name': u'Lennon', -... 'birthday': u'1940-10-9' -... } ->>> p = Person(data, prefix='person1') ->>> p.errors['first_name'] -[u'This field is required.'] ->>> p.errors['last_name'] -[u'This field is required.'] ->>> p.errors['birthday'] -[u'This field is required.'] - -With prefixes, a single data dictionary can hold data for multiple instances -of the same form. ->>> data = { -... 'person1-first_name': u'John', -... 'person1-last_name': u'Lennon', -... 'person1-birthday': u'1940-10-9', -... 'person2-first_name': u'Jim', -... 'person2-last_name': u'Morrison', -... 'person2-birthday': u'1943-12-8' -... } ->>> p1 = Person(data, prefix='person1') ->>> p1.is_valid() -True ->>> p1.cleaned_data['first_name'] -u'John' ->>> p1.cleaned_data['last_name'] -u'Lennon' ->>> p1.cleaned_data['birthday'] -datetime.date(1940, 10, 9) ->>> p2 = Person(data, prefix='person2') ->>> p2.is_valid() -True ->>> p2.cleaned_data['first_name'] -u'Jim' ->>> p2.cleaned_data['last_name'] -u'Morrison' ->>> p2.cleaned_data['birthday'] -datetime.date(1943, 12, 8) - -By default, forms append a hyphen between the prefix and the field name, but a -form can alter that behavior by implementing the add_prefix() method. This -method takes a field name and returns the prefixed field, according to -self.prefix. ->>> class Person(Form): -... first_name = CharField() -... last_name = CharField() -... birthday = DateField() -... def add_prefix(self, field_name): -... return self.prefix and '%s-prefix-%s' % (self.prefix, field_name) or field_name ->>> p = Person(prefix='foo') ->>> print 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> -<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> -<li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" /></li> ->>> data = { -... 'foo-prefix-first_name': u'John', -... 'foo-prefix-last_name': u'Lennon', -... 'foo-prefix-birthday': u'1940-10-9' -... } ->>> p = Person(data, prefix='foo') ->>> p.is_valid() -True ->>> p.cleaned_data['first_name'] -u'John' ->>> p.cleaned_data['last_name'] -u'Lennon' ->>> p.cleaned_data['birthday'] -datetime.date(1940, 10, 9) - -# Forms with NullBooleanFields ################################################ - -NullBooleanField is a bit of a special case because its presentation (widget) -is different than its data. This is handled transparently, though. - ->>> class Person(Form): -... name = CharField() -... is_cool = NullBooleanField() ->>> p = Person({'name': u'Joe'}, auto_id=False) ->>> print p['is_cool'] -<select name="is_cool"> -<option value="1" selected="selected">Unknown</option> -<option value="2">Yes</option> -<option value="3">No</option> -</select> ->>> p = Person({'name': u'Joe', 'is_cool': u'1'}, auto_id=False) ->>> print p['is_cool'] -<select name="is_cool"> -<option value="1" selected="selected">Unknown</option> -<option value="2">Yes</option> -<option value="3">No</option> -</select> ->>> p = Person({'name': u'Joe', 'is_cool': u'2'}, auto_id=False) ->>> print p['is_cool'] -<select name="is_cool"> -<option value="1">Unknown</option> -<option value="2" selected="selected">Yes</option> -<option value="3">No</option> -</select> ->>> p = Person({'name': u'Joe', 'is_cool': u'3'}, auto_id=False) ->>> print p['is_cool'] -<select name="is_cool"> -<option value="1">Unknown</option> -<option value="2">Yes</option> -<option value="3" selected="selected">No</option> -</select> ->>> p = Person({'name': u'Joe', 'is_cool': True}, auto_id=False) ->>> print p['is_cool'] -<select name="is_cool"> -<option value="1">Unknown</option> -<option value="2" selected="selected">Yes</option> -<option value="3">No</option> -</select> ->>> p = Person({'name': u'Joe', 'is_cool': False}, auto_id=False) ->>> print p['is_cool'] -<select name="is_cool"> -<option value="1">Unknown</option> -<option value="2">Yes</option> -<option value="3" selected="selected">No</option> -</select> - -# Forms with FileFields ################################################ - -FileFields are a special case because they take their data from the request.FILES, -not request.POST. - ->>> class FileForm(Form): -... file1 = FileField() ->>> f = FileForm(auto_id=False) ->>> print f -<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr> - ->>> f = FileForm(data={}, files={}, auto_id=False) ->>> print f -<tr><th>File1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="file" name="file1" /></td></tr> - ->>> f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', '')}, auto_id=False) ->>> print f -<tr><th>File1:</th><td><ul class="errorlist"><li>The submitted file is empty.</li></ul><input type="file" name="file1" /></td></tr> - ->>> f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False) ->>> print f -<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> - ->>> f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', 'some content')}, auto_id=False) ->>> print f -<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr> ->>> f.is_valid() -True - ->>> f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')}, auto_id=False) ->>> print f -<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr> - -# Basic form processing in a view ############################################# - ->>> from django.template import Template, Context ->>> class UserRegistration(Form): -... username = CharField(max_length=10) -... password1 = CharField(widget=PasswordInput) -... password2 = CharField(widget=PasswordInput) -... def clean(self): -... if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: -... raise ValidationError(u'Please make sure your passwords match.') -... return self.cleaned_data ->>> def my_function(method, post_data): -... if method == 'POST': -... form = UserRegistration(post_data, auto_id=False) -... else: -... form = UserRegistration(auto_id=False) -... if form.is_valid(): -... return 'VALID: %r' % form.cleaned_data -... t = Template('<form action="" method="post">\n<table>\n{{ form }}\n</table>\n<input type="submit" />\n</form>') -... return t.render(Context({'form': form})) - -Case 1: GET (an empty form, with no errors). ->>> print my_function('GET', {}) -<form action="" method="post"> -<table> -<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" /></td></tr> -<tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr> -<tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr> -</table> -<input type="submit" /> -</form> - -Case 2: POST with erroneous data (a redisplayed form, with errors). ->>> print my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}) -<form action="" method="post"> -<table> -<tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr> -<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> -<tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr> -<tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr> -</table> -<input type="submit" /> -</form> - -Case 3: POST with valid data (the success message). ->>> print my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}) -VALID: {'username': u'adrian', 'password1': u'secret', 'password2': u'secret'} - -# Some ideas for using templates with forms ################################### - ->>> class UserRegistration(Form): -... username = CharField(max_length=10, help_text="Good luck picking a username that doesn't already exist.") -... password1 = CharField(widget=PasswordInput) -... password2 = CharField(widget=PasswordInput) -... def clean(self): -... if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: -... raise ValidationError(u'Please make sure your passwords match.') -... return self.cleaned_data - -You have full flexibility in displaying form fields in a template. Just pass a -Form instance to the template, and use "dot" access to refer to individual -fields. Note, however, that this flexibility comes with the responsibility of -displaying all the errors, including any that might not be associated with a -particular field. ->>> t = Template('''<form action=""> -... {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p> -... {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p> -... {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p> -... <input type="submit" /> -... </form>''') ->>> print t.render(Context({'form': UserRegistration(auto_id=False)})) -<form action=""> -<p><label>Your username: <input type="text" name="username" maxlength="10" /></label></p> -<p><label>Password: <input type="password" name="password1" /></label></p> -<p><label>Password (again): <input type="password" name="password2" /></label></p> -<input type="submit" /> -</form> ->>> print t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})) -<form action=""> -<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p> -<ul class="errorlist"><li>This field is required.</li></ul><p><label>Password: <input type="password" name="password1" /></label></p> -<ul class="errorlist"><li>This field is required.</li></ul><p><label>Password (again): <input type="password" name="password2" /></label></p> -<input type="submit" /> -</form> - -Use form.[field].label to output a field's label. You can specify the label for -a field by using the 'label' argument to a Field class. If you don't specify -'label', Django will use the field name with underscores converted to spaces, -and the initial letter capitalized. ->>> t = Template('''<form action=""> -... <p><label>{{ form.username.label }}: {{ form.username }}</label></p> -... <p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p> -... <p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p> -... <input type="submit" /> -... </form>''') ->>> print t.render(Context({'form': UserRegistration(auto_id=False)})) -<form action=""> -<p><label>Username: <input type="text" name="username" maxlength="10" /></label></p> -<p><label>Password1: <input type="password" name="password1" /></label></p> -<p><label>Password2: <input type="password" name="password2" /></label></p> -<input type="submit" /> -</form> - -User form.[field].label_tag to output a field's label with a <label> tag -wrapped around it, but *only* if the given field has an "id" attribute. -Recall from above that passing the "auto_id" argument to a Form gives each -field an "id" attribute. ->>> t = Template('''<form action=""> -... <p>{{ form.username.label_tag }}: {{ form.username }}</p> -... <p>{{ form.password1.label_tag }}: {{ form.password1 }}</p> -... <p>{{ form.password2.label_tag }}: {{ form.password2 }}</p> -... <input type="submit" /> -... </form>''') ->>> print t.render(Context({'form': UserRegistration(auto_id=False)})) -<form action=""> -<p>Username: <input type="text" name="username" maxlength="10" /></p> -<p>Password1: <input type="password" name="password1" /></p> -<p>Password2: <input type="password" name="password2" /></p> -<input type="submit" /> -</form> ->>> print t.render(Context({'form': UserRegistration(auto_id='id_%s')})) -<form action=""> -<p><label for="id_username">Username</label>: <input id="id_username" type="text" name="username" maxlength="10" /></p> -<p><label for="id_password1">Password1</label>: <input type="password" name="password1" id="id_password1" /></p> -<p><label for="id_password2">Password2</label>: <input type="password" name="password2" id="id_password2" /></p> -<input type="submit" /> -</form> - -User form.[field].help_text to output a field's help text. If the given field -does not have help text, nothing will be output. ->>> t = Template('''<form action=""> -... <p>{{ form.username.label_tag }}: {{ form.username }}<br />{{ form.username.help_text }}</p> -... <p>{{ form.password1.label_tag }}: {{ form.password1 }}</p> -... <p>{{ form.password2.label_tag }}: {{ form.password2 }}</p> -... <input type="submit" /> -... </form>''') ->>> print t.render(Context({'form': UserRegistration(auto_id=False)})) -<form action=""> -<p>Username: <input type="text" name="username" maxlength="10" /><br />Good luck picking a username that doesn't already exist.</p> -<p>Password1: <input type="password" name="password1" /></p> -<p>Password2: <input type="password" name="password2" /></p> -<input type="submit" /> -</form> ->>> Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})) -u'' - -The label_tag() method takes an optional attrs argument: a dictionary of HTML -attributes to add to the <label> tag. ->>> f = UserRegistration(auto_id='id_%s') ->>> for bf in f: -... print bf.label_tag(attrs={'class': 'pretty'}) -<label for="id_username" class="pretty">Username</label> -<label for="id_password1" class="pretty">Password1</label> -<label for="id_password2" class="pretty">Password2</label> - -To display the errors that aren't associated with a particular field -- e.g., -the errors caused by Form.clean() -- use {{ form.non_field_errors }} in the -template. If used on its own, it is displayed as a <ul> (or an empty string, if -the list of errors is empty). You can also use it in {% if %} statements. ->>> t = Template('''<form action=""> -... {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p> -... {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p> -... {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p> -... <input type="submit" /> -... </form>''') ->>> print t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})) -<form action=""> -<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p> -<p><label>Password: <input type="password" name="password1" /></label></p> -<p><label>Password (again): <input type="password" name="password2" /></label></p> -<input type="submit" /> -</form> ->>> t = Template('''<form action=""> -... {{ form.non_field_errors }} -... {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p> -... {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p> -... {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p> -... <input type="submit" /> -... </form>''') ->>> print t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})) -<form action=""> -<ul class="errorlist"><li>Please make sure your passwords match.</li></ul> -<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p> -<p><label>Password: <input type="password" name="password1" /></label></p> -<p><label>Password (again): <input type="password" name="password2" /></label></p> -<input type="submit" /> -</form> - - -# The empty_permitted attribute ############################################## - -Sometimes (pretty much in formsets) we want to allow a form to pass validation -if it is completely empty. We can accomplish this by using the empty_permitted -agrument to a form constructor. - ->>> class SongForm(Form): -... artist = CharField() -... name = CharField() - -First let's show what happens id empty_permitted=False (the default): - ->>> data = {'artist': '', 'song': ''} - ->>> form = SongForm(data, empty_permitted=False) ->>> form.is_valid() -False ->>> form.errors -{'name': [u'This field is required.'], 'artist': [u'This field is required.']} ->>> form.cleaned_data -Traceback (most recent call last): -... -AttributeError: 'SongForm' object has no attribute 'cleaned_data' - - -Now let's show what happens when empty_permitted=True and the form is empty. - ->>> form = SongForm(data, empty_permitted=True) ->>> form.is_valid() -True ->>> form.errors -{} ->>> form.cleaned_data -{} - -But if we fill in data for one of the fields, the form is no longer empty and -the whole thing must pass validation. - ->>> data = {'artist': 'The Doors', 'song': ''} ->>> form = SongForm(data, empty_permitted=False) ->>> form.is_valid() -False ->>> form.errors -{'name': [u'This field is required.']} ->>> form.cleaned_data -Traceback (most recent call last): -... -AttributeError: 'SongForm' object has no attribute 'cleaned_data' - -If a field is not given in the data then None is returned for its data. Lets -make sure that when checking for empty_permitted that None is treated -accordingly. - ->>> data = {'artist': None, 'song': ''} ->>> form = SongForm(data, empty_permitted=True) ->>> form.is_valid() -True - -However, we *really* need to be sure we are checking for None as any data in -initial that returns False on a boolean call needs to be treated literally. - ->>> class PriceForm(Form): -... amount = FloatField() -... qty = IntegerField() - ->>> data = {'amount': '0.0', 'qty': ''} ->>> form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True) ->>> form.is_valid() -True - -# Extracting hidden and visible fields ###################################### - ->>> class SongForm(Form): -... token = CharField(widget=HiddenInput) -... artist = CharField() -... name = CharField() ->>> form = SongForm() ->>> [f.name for f in form.hidden_fields()] -['token'] ->>> [f.name for f in form.visible_fields()] -['artist', 'name'] - -# Hidden initial input gets its own unique id ################################ - ->>> class MyForm(Form): -... field1 = CharField(max_length=50, show_hidden_initial=True) ->>> print MyForm() -<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> - -# The error_html_class and required_html_class attributes #################### - ->>> class Person(Form): -... name = CharField() -... is_cool = NullBooleanField() -... email = EmailField(required=False) -... age = IntegerField() - ->>> p = Person({}) ->>> p.error_css_class = 'error' ->>> p.required_css_class = 'required' - ->>> print 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> -<li class="required"><label for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> -<option value="1" selected="selected">Unknown</option> -<option value="2">Yes</option> -<option value="3">No</option> -</select></li> -<li><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></li> -<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> - ->>> print p.as_p() -<ul class="errorlist"><li>This field is required.</li></ul> -<p class="required error"><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p> -<p class="required"><label for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> -<option value="1" selected="selected">Unknown</option> -<option value="2">Yes</option> -<option value="3">No</option> -</select></p> -<p><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></p> -<ul class="errorlist"><li>This field is required.</li></ul> -<p class="required error"><label for="id_age">Age:</label> <input type="text" name="age" id="id_age" /></p> - ->>> print 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> -<tr class="required"><th><label for="id_is_cool">Is cool:</label></th><td><select name="is_cool" id="id_is_cool"> -<option value="1" selected="selected">Unknown</option> -<option value="2">Yes</option> -<option value="3">No</option> -</select></td></tr> -<tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email" /></td></tr> -<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> - - - -# Checking that the label for SplitDateTimeField is not being displayed ##### - ->>> class EventForm(Form): -... happened_at = SplitDateTimeField(widget=widgets.SplitHiddenDateTimeWidget) -... ->>> form = EventForm() ->>> 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" />' - -""" diff --git a/tests/regressiontests/forms/formsets.py b/tests/regressiontests/forms/formsets.py deleted file mode 100644 index f8b8ae2a8a..0000000000 --- a/tests/regressiontests/forms/formsets.py +++ /dev/null @@ -1,762 +0,0 @@ -# -*- coding: utf-8 -*- -from django.test.testcases import TestCase -from django.forms.forms import Form -from django.forms.fields import CharField, IntegerField -from django.forms.formsets import formset_factory -tests = """ -# Basic FormSet creation and usage ############################################ - -FormSet allows us to use multiple instance of the same form on 1 page. For now, -the best way to create a FormSet is by using the formset_factory function. - ->>> from django.forms import Form, CharField, IntegerField, ValidationError ->>> from django.forms.formsets import formset_factory, BaseFormSet - ->>> class Choice(Form): -... choice = CharField() -... votes = IntegerField() - ->>> ChoiceFormSet = formset_factory(Choice) - -A FormSet constructor takes the same arguments as Form. Let's create a FormSet -for adding data. By default, it displays 1 blank form. It can display more, -but we'll look at how to do so later. - ->>> formset = ChoiceFormSet(auto_id=False, prefix='choices') ->>> print formset -<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" /> -<tr><th>Choice:</th><td><input type="text" name="choices-0-choice" /></td></tr> -<tr><th>Votes:</th><td><input type="text" name="choices-0-votes" /></td></tr> - - -On thing to note is that there needs to be a special value in the data. This -value tells the FormSet how many forms were displayed so it can tell how -many forms it needs to clean and validate. You could use javascript to create -new forms on the client side, but they won't get validated unless you increment -the TOTAL_FORMS field appropriately. - ->>> data = { -... 'choices-TOTAL_FORMS': '1', # the number of forms rendered -... 'choices-INITIAL_FORMS': '0', # the number of forms with initial data -... 'choices-MAX_NUM_FORMS': '0', # max number of forms -... 'choices-0-choice': 'Calexico', -... 'choices-0-votes': '100', -... } - -We treat FormSet pretty much like we would treat a normal Form. FormSet has an -is_valid method, and a cleaned_data or errors attribute depending on whether all -the forms passed validation. However, unlike a Form instance, cleaned_data and -errors will be a list of dicts rather than just a single dict. - ->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices') ->>> formset.is_valid() -True ->>> [form.cleaned_data for form in formset.forms] -[{'votes': 100, 'choice': u'Calexico'}] - -If a FormSet was not passed any data, its is_valid method should return False. ->>> formset = ChoiceFormSet() ->>> formset.is_valid() -False - -FormSet instances can also have an error attribute if validation failed for -any of the forms. - ->>> data = { -... 'choices-TOTAL_FORMS': '1', # the number of forms rendered -... 'choices-INITIAL_FORMS': '0', # the number of forms with initial data -... 'choices-MAX_NUM_FORMS': '0', # max number of forms -... 'choices-0-choice': 'Calexico', -... 'choices-0-votes': '', -... } - ->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices') ->>> formset.is_valid() -False ->>> formset.errors -[{'votes': [u'This field is required.']}] - - -We can also prefill a FormSet with existing data by providing an ``initial`` -argument to the constructor. ``initial`` should be a list of dicts. By default, -an extra blank form is included. - ->>> initial = [{'choice': u'Calexico', 'votes': 100}] ->>> formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') ->>> for form in formset.forms: -... print form.as_ul() -<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> -<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> -<li>Choice: <input type="text" name="choices-1-choice" /></li> -<li>Votes: <input type="text" name="choices-1-votes" /></li> - - -Let's simulate what would happen if we submitted this form. - ->>> data = { -... 'choices-TOTAL_FORMS': '2', # the number of forms rendered -... 'choices-INITIAL_FORMS': '1', # the number of forms with initial data -... 'choices-MAX_NUM_FORMS': '0', # max number of forms -... 'choices-0-choice': 'Calexico', -... 'choices-0-votes': '100', -... 'choices-1-choice': '', -... 'choices-1-votes': '', -... } - ->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices') ->>> formset.is_valid() -True ->>> [form.cleaned_data for form in formset.forms] -[{'votes': 100, 'choice': u'Calexico'}, {}] - -But the second form was blank! Shouldn't we get some errors? No. If we display -a form as blank, it's ok for it to be submitted as blank. If we fill out even -one of the fields of a blank form though, it will be validated. We may want to -required that at least x number of forms are completed, but we'll show how to -handle that later. - ->>> data = { -... 'choices-TOTAL_FORMS': '2', # the number of forms rendered -... 'choices-INITIAL_FORMS': '1', # the number of forms with initial data -... 'choices-MAX_NUM_FORMS': '0', # max number of forms -... 'choices-0-choice': 'Calexico', -... 'choices-0-votes': '100', -... 'choices-1-choice': 'The Decemberists', -... 'choices-1-votes': '', # missing value -... } - ->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices') ->>> formset.is_valid() -False ->>> formset.errors -[{}, {'votes': [u'This field is required.']}] - -If we delete data that was pre-filled, we should get an error. Simply removing -data from form fields isn't the proper way to delete it. We'll see how to -handle that case later. - ->>> data = { -... 'choices-TOTAL_FORMS': '2', # the number of forms rendered -... 'choices-INITIAL_FORMS': '1', # the number of forms with initial data -... 'choices-MAX_NUM_FORMS': '0', # max number of forms -... 'choices-0-choice': '', # deleted value -... 'choices-0-votes': '', # deleted value -... 'choices-1-choice': '', -... 'choices-1-votes': '', -... } - ->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices') ->>> formset.is_valid() -False ->>> formset.errors -[{'votes': [u'This field is required.'], 'choice': [u'This field is required.']}, {}] - - -# Displaying more than 1 blank form ########################################### - -We can also display more than 1 empty form at a time. To do so, pass a -extra argument to formset_factory. - ->>> ChoiceFormSet = formset_factory(Choice, extra=3) - ->>> formset = ChoiceFormSet(auto_id=False, prefix='choices') ->>> for form in formset.forms: -... print form.as_ul() -<li>Choice: <input type="text" name="choices-0-choice" /></li> -<li>Votes: <input type="text" name="choices-0-votes" /></li> -<li>Choice: <input type="text" name="choices-1-choice" /></li> -<li>Votes: <input type="text" name="choices-1-votes" /></li> -<li>Choice: <input type="text" name="choices-2-choice" /></li> -<li>Votes: <input type="text" name="choices-2-votes" /></li> - -Since we displayed every form as blank, we will also accept them back as blank. -This may seem a little strange, but later we will show how to require a minimum -number of forms to be completed. - ->>> data = { -... 'choices-TOTAL_FORMS': '3', # the number of forms rendered -... 'choices-INITIAL_FORMS': '0', # the number of forms with initial data -... 'choices-MAX_NUM_FORMS': '0', # max number of forms -... 'choices-0-choice': '', -... 'choices-0-votes': '', -... 'choices-1-choice': '', -... 'choices-1-votes': '', -... 'choices-2-choice': '', -... 'choices-2-votes': '', -... } - ->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices') ->>> formset.is_valid() -True ->>> [form.cleaned_data for form in formset.forms] -[{}, {}, {}] - - -We can just fill out one of the forms. - ->>> data = { -... 'choices-TOTAL_FORMS': '3', # the number of forms rendered -... 'choices-INITIAL_FORMS': '0', # the number of forms with initial data -... 'choices-MAX_NUM_FORMS': '0', # max number of forms -... 'choices-0-choice': 'Calexico', -... 'choices-0-votes': '100', -... 'choices-1-choice': '', -... 'choices-1-votes': '', -... 'choices-2-choice': '', -... 'choices-2-votes': '', -... } - ->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices') ->>> formset.is_valid() -True ->>> [form.cleaned_data for form in formset.forms] -[{'votes': 100, 'choice': u'Calexico'}, {}, {}] - - -And once again, if we try to partially complete a form, validation will fail. - ->>> data = { -... 'choices-TOTAL_FORMS': '3', # the number of forms rendered -... 'choices-INITIAL_FORMS': '0', # the number of forms with initial data -... 'choices-MAX_NUM_FORMS': '0', # max number of forms -... 'choices-0-choice': 'Calexico', -... 'choices-0-votes': '100', -... 'choices-1-choice': 'The Decemberists', -... 'choices-1-votes': '', # missing value -... 'choices-2-choice': '', -... 'choices-2-votes': '', -... } - ->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices') ->>> formset.is_valid() -False ->>> formset.errors -[{}, {'votes': [u'This field is required.']}, {}] - - -The extra argument also works when the formset is pre-filled with initial -data. - ->>> initial = [{'choice': u'Calexico', 'votes': 100}] ->>> formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') ->>> for form in formset.forms: -... print form.as_ul() -<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> -<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> -<li>Choice: <input type="text" name="choices-1-choice" /></li> -<li>Votes: <input type="text" name="choices-1-votes" /></li> -<li>Choice: <input type="text" name="choices-2-choice" /></li> -<li>Votes: <input type="text" name="choices-2-votes" /></li> -<li>Choice: <input type="text" name="choices-3-choice" /></li> -<li>Votes: <input type="text" name="choices-3-votes" /></li> - -Make sure retrieving an empty form works, and it shows up in the form list - ->>> formset.empty_form.empty_permitted -True ->>> print formset.empty_form.as_ul() -<li>Choice: <input type="text" name="choices-__prefix__-choice" /></li> -<li>Votes: <input type="text" name="choices-__prefix__-votes" /></li> - -# FormSets with deletion ###################################################### - -We can easily add deletion ability to a FormSet with an argument to -formset_factory. This will add a boolean field to each form instance. When -that boolean field is True, the form will be in formset.deleted_forms - ->>> ChoiceFormSet = formset_factory(Choice, can_delete=True) - ->>> initial = [{'choice': u'Calexico', 'votes': 100}, {'choice': u'Fergie', 'votes': 900}] ->>> formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') ->>> for form in formset.forms: -... print form.as_ul() -<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> -<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> -<li>Delete: <input type="checkbox" name="choices-0-DELETE" /></li> -<li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li> -<li>Votes: <input type="text" name="choices-1-votes" value="900" /></li> -<li>Delete: <input type="checkbox" name="choices-1-DELETE" /></li> -<li>Choice: <input type="text" name="choices-2-choice" /></li> -<li>Votes: <input type="text" name="choices-2-votes" /></li> -<li>Delete: <input type="checkbox" name="choices-2-DELETE" /></li> - -To delete something, we just need to set that form's special delete field to -'on'. Let's go ahead and delete Fergie. - ->>> data = { -... 'choices-TOTAL_FORMS': '3', # the number of forms rendered -... 'choices-INITIAL_FORMS': '2', # the number of forms with initial data -... 'choices-MAX_NUM_FORMS': '0', # max number of forms -... 'choices-0-choice': 'Calexico', -... 'choices-0-votes': '100', -... 'choices-0-DELETE': '', -... 'choices-1-choice': 'Fergie', -... 'choices-1-votes': '900', -... 'choices-1-DELETE': 'on', -... 'choices-2-choice': '', -... 'choices-2-votes': '', -... 'choices-2-DELETE': '', -... } - ->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices') ->>> formset.is_valid() -True ->>> [form.cleaned_data for form in formset.forms] -[{'votes': 100, 'DELETE': False, 'choice': u'Calexico'}, {'votes': 900, 'DELETE': True, 'choice': u'Fergie'}, {}] ->>> [form.cleaned_data for form in formset.deleted_forms] -[{'votes': 900, 'DELETE': True, 'choice': u'Fergie'}] - -If we fill a form with something and then we check the can_delete checkbox for -that form, that form's errors should not make the entire formset invalid since -it's going to be deleted. - ->>> class CheckForm(Form): -... field = IntegerField(min_value=100) - ->>> data = { -... 'check-TOTAL_FORMS': '3', # the number of forms rendered -... 'check-INITIAL_FORMS': '2', # the number of forms with initial data -... 'check-MAX_NUM_FORMS': '0', # max number of forms -... 'check-0-field': '200', -... 'check-0-DELETE': '', -... 'check-1-field': '50', -... 'check-1-DELETE': 'on', -... 'check-2-field': '', -... 'check-2-DELETE': '', -... } ->>> CheckFormSet = formset_factory(CheckForm, can_delete=True) ->>> formset = CheckFormSet(data, prefix='check') ->>> formset.is_valid() -True - -If we remove the deletion flag now we will have our validation back. - ->>> data['check-1-DELETE'] = '' ->>> formset = CheckFormSet(data, prefix='check') ->>> formset.is_valid() -False - -Should be able to get deleted_forms from a valid formset even if a -deleted form would have been invalid. - ->>> class Person(Form): -... name = CharField() - ->>> PeopleForm = formset_factory( -... form=Person, -... can_delete=True) - ->>> p = PeopleForm( -... {'form-0-name': u'', 'form-0-DELETE': u'on', # no name! -... 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, -... 'form-MAX_NUM_FORMS': 1}) - ->>> p.is_valid() -True ->>> len(p.deleted_forms) -1 - -# FormSets with ordering ###################################################### - -We can also add ordering ability to a FormSet with an agrument to -formset_factory. This will add a integer field to each form instance. When -form validation succeeds, [form.cleaned_data for form in formset.forms] will have the data in the correct -order specified by the ordering fields. If a number is duplicated in the set -of ordering fields, for instance form 0 and form 3 are both marked as 1, then -the form index used as a secondary ordering criteria. In order to put -something at the front of the list, you'd need to set it's order to 0. - ->>> ChoiceFormSet = formset_factory(Choice, can_order=True) - ->>> initial = [{'choice': u'Calexico', 'votes': 100}, {'choice': u'Fergie', 'votes': 900}] ->>> formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') ->>> for form in formset.forms: -... print form.as_ul() -<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> -<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> -<li>Order: <input type="text" name="choices-0-ORDER" value="1" /></li> -<li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li> -<li>Votes: <input type="text" name="choices-1-votes" value="900" /></li> -<li>Order: <input type="text" name="choices-1-ORDER" value="2" /></li> -<li>Choice: <input type="text" name="choices-2-choice" /></li> -<li>Votes: <input type="text" name="choices-2-votes" /></li> -<li>Order: <input type="text" name="choices-2-ORDER" /></li> - ->>> data = { -... 'choices-TOTAL_FORMS': '3', # the number of forms rendered -... 'choices-INITIAL_FORMS': '2', # the number of forms with initial data -... 'choices-MAX_NUM_FORMS': '0', # max number of forms -... 'choices-0-choice': 'Calexico', -... 'choices-0-votes': '100', -... 'choices-0-ORDER': '1', -... 'choices-1-choice': 'Fergie', -... 'choices-1-votes': '900', -... 'choices-1-ORDER': '2', -... 'choices-2-choice': 'The Decemberists', -... 'choices-2-votes': '500', -... 'choices-2-ORDER': '0', -... } - ->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices') ->>> formset.is_valid() -True ->>> for form in formset.ordered_forms: -... print form.cleaned_data -{'votes': 500, 'ORDER': 0, 'choice': u'The Decemberists'} -{'votes': 100, 'ORDER': 1, 'choice': u'Calexico'} -{'votes': 900, 'ORDER': 2, 'choice': u'Fergie'} - -Ordering fields are allowed to be left blank, and if they *are* left blank, -they will be sorted below everything else. - ->>> data = { -... 'choices-TOTAL_FORMS': '4', # the number of forms rendered -... 'choices-INITIAL_FORMS': '3', # the number of forms with initial data -... 'choices-MAX_NUM_FORMS': '0', # max number of forms -... 'choices-0-choice': 'Calexico', -... 'choices-0-votes': '100', -... 'choices-0-ORDER': '1', -... 'choices-1-choice': 'Fergie', -... 'choices-1-votes': '900', -... 'choices-1-ORDER': '2', -... 'choices-2-choice': 'The Decemberists', -... 'choices-2-votes': '500', -... 'choices-2-ORDER': '', -... 'choices-3-choice': 'Basia Bulat', -... 'choices-3-votes': '50', -... 'choices-3-ORDER': '', -... } - ->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices') ->>> formset.is_valid() -True ->>> for form in formset.ordered_forms: -... print form.cleaned_data -{'votes': 100, 'ORDER': 1, 'choice': u'Calexico'} -{'votes': 900, 'ORDER': 2, 'choice': u'Fergie'} -{'votes': 500, 'ORDER': None, 'choice': u'The Decemberists'} -{'votes': 50, 'ORDER': None, 'choice': u'Basia Bulat'} - -Ordering should work with blank fieldsets. - ->>> data = { -... 'choices-TOTAL_FORMS': '3', # the number of forms rendered -... 'choices-INITIAL_FORMS': '0', # the number of forms with initial data -... 'choices-MAX_NUM_FORMS': '0', # max number of forms -... } - ->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices') ->>> formset.is_valid() -True ->>> for form in formset.ordered_forms: -... print form.cleaned_data - -# FormSets with ordering + deletion ########################################### - -Let's try throwing ordering and deletion into the same form. - ->>> ChoiceFormSet = formset_factory(Choice, can_order=True, can_delete=True) - ->>> initial = [ -... {'choice': u'Calexico', 'votes': 100}, -... {'choice': u'Fergie', 'votes': 900}, -... {'choice': u'The Decemberists', 'votes': 500}, -... ] ->>> formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') ->>> for form in formset.forms: -... print form.as_ul() -<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> -<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> -<li>Order: <input type="text" name="choices-0-ORDER" value="1" /></li> -<li>Delete: <input type="checkbox" name="choices-0-DELETE" /></li> -<li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li> -<li>Votes: <input type="text" name="choices-1-votes" value="900" /></li> -<li>Order: <input type="text" name="choices-1-ORDER" value="2" /></li> -<li>Delete: <input type="checkbox" name="choices-1-DELETE" /></li> -<li>Choice: <input type="text" name="choices-2-choice" value="The Decemberists" /></li> -<li>Votes: <input type="text" name="choices-2-votes" value="500" /></li> -<li>Order: <input type="text" name="choices-2-ORDER" value="3" /></li> -<li>Delete: <input type="checkbox" name="choices-2-DELETE" /></li> -<li>Choice: <input type="text" name="choices-3-choice" /></li> -<li>Votes: <input type="text" name="choices-3-votes" /></li> -<li>Order: <input type="text" name="choices-3-ORDER" /></li> -<li>Delete: <input type="checkbox" name="choices-3-DELETE" /></li> - -Let's delete Fergie, and put The Decemberists ahead of Calexico. - ->>> data = { -... 'choices-TOTAL_FORMS': '4', # the number of forms rendered -... 'choices-INITIAL_FORMS': '3', # the number of forms with initial data -... 'choices-MAX_NUM_FORMS': '0', # max number of forms -... 'choices-0-choice': 'Calexico', -... 'choices-0-votes': '100', -... 'choices-0-ORDER': '1', -... 'choices-0-DELETE': '', -... 'choices-1-choice': 'Fergie', -... 'choices-1-votes': '900', -... 'choices-1-ORDER': '2', -... 'choices-1-DELETE': 'on', -... 'choices-2-choice': 'The Decemberists', -... 'choices-2-votes': '500', -... 'choices-2-ORDER': '0', -... 'choices-2-DELETE': '', -... 'choices-3-choice': '', -... 'choices-3-votes': '', -... 'choices-3-ORDER': '', -... 'choices-3-DELETE': '', -... } - ->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices') ->>> formset.is_valid() -True ->>> for form in formset.ordered_forms: -... print form.cleaned_data -{'votes': 500, 'DELETE': False, 'ORDER': 0, 'choice': u'The Decemberists'} -{'votes': 100, 'DELETE': False, 'ORDER': 1, 'choice': u'Calexico'} ->>> [form.cleaned_data for form in formset.deleted_forms] -[{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': u'Fergie'}] - -Should be able to get ordered forms from a valid formset even if a -deleted form would have been invalid. - ->>> class Person(Form): -... name = CharField() - ->>> PeopleForm = formset_factory( -... form=Person, -... can_delete=True, -... can_order=True) - ->>> p = PeopleForm( -... {'form-0-name': u'', 'form-0-DELETE': u'on', # no name! -... 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, -... 'form-MAX_NUM_FORMS': 1}) - ->>> p.is_valid() -True ->>> p.ordered_forms -[] - -# FormSet clean hook ########################################################## - -FormSets have a hook for doing extra validation that shouldn't be tied to any -particular form. It follows the same pattern as the clean hook on Forms. - -Let's define a FormSet that takes a list of favorite drinks, but raises am -error if there are any duplicates. - ->>> class FavoriteDrinkForm(Form): -... name = CharField() -... - ->>> class BaseFavoriteDrinksFormSet(BaseFormSet): -... def clean(self): -... seen_drinks = [] -... for drink in self.cleaned_data: -... if drink['name'] in seen_drinks: -... raise ValidationError('You may only specify a drink once.') -... seen_drinks.append(drink['name']) -... - ->>> FavoriteDrinksFormSet = formset_factory(FavoriteDrinkForm, -... formset=BaseFavoriteDrinksFormSet, extra=3) - -We start out with a some duplicate data. - ->>> data = { -... 'drinks-TOTAL_FORMS': '2', # the number of forms rendered -... 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data -... 'drinks-MAX_NUM_FORMS': '0', # max number of forms -... 'drinks-0-name': 'Gin and Tonic', -... 'drinks-1-name': 'Gin and Tonic', -... } - ->>> formset = FavoriteDrinksFormSet(data, prefix='drinks') ->>> formset.is_valid() -False - -Any errors raised by formset.clean() are available via the -formset.non_form_errors() method. - ->>> for error in formset.non_form_errors(): -... print error -You may only specify a drink once. - - -Make sure we didn't break the valid case. - ->>> data = { -... 'drinks-TOTAL_FORMS': '2', # the number of forms rendered -... 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data -... 'drinks-MAX_NUM_FORMS': '0', # max number of forms -... 'drinks-0-name': 'Gin and Tonic', -... 'drinks-1-name': 'Bloody Mary', -... } - ->>> formset = FavoriteDrinksFormSet(data, prefix='drinks') ->>> formset.is_valid() -True ->>> for error in formset.non_form_errors(): -... print error - -# Limiting the maximum number of forms ######################################## - -# Base case for max_num. - -# When not passed, max_num will take its default value of None, i.e. unlimited -# number of forms, only controlled by the value of the extra parameter. - ->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3) ->>> formset = LimitedFavoriteDrinkFormSet() ->>> for form in formset.forms: -... print form -<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr> -<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr> -<tr><th><label for="id_form-2-name">Name:</label></th><td><input type="text" name="form-2-name" id="id_form-2-name" /></td></tr> - -# If max_num is 0 then no form is rendered at all. - ->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=0) ->>> formset = LimitedFavoriteDrinkFormSet() ->>> for form in formset.forms: -... print form - ->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=5, max_num=2) ->>> formset = LimitedFavoriteDrinkFormSet() ->>> for form in formset.forms: -... print form -<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr> -<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr> - -# Ensure that max_num has no effect when extra is less than max_num. - ->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2) ->>> formset = LimitedFavoriteDrinkFormSet() ->>> for form in formset.forms: -... print form -<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr> - -# max_num with initial data - -# When not passed, max_num will take its default value of None, i.e. unlimited -# number of forms, only controlled by the values of the initial and extra -# parameters. - ->>> initial = [ -... {'name': 'Fernet and Coke'}, -... ] ->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1) ->>> formset = LimitedFavoriteDrinkFormSet(initial=initial) ->>> for form in formset.forms: -... print form -<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Fernet and Coke" id="id_form-0-name" /></td></tr> -<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr> - -# If max_num is 0 then no form is rendered at all, even if extra and initial -# are specified. - ->>> initial = [ -... {'name': 'Fernet and Coke'}, -... {'name': 'Bloody Mary'}, -... ] ->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=0) ->>> formset = LimitedFavoriteDrinkFormSet(initial=initial) ->>> for form in formset.forms: -... print form - -# More initial forms than max_num will result in only the first max_num of -# them to be displayed with no extra forms. - ->>> initial = [ -... {'name': 'Gin Tonic'}, -... {'name': 'Bloody Mary'}, -... {'name': 'Jack and Coke'}, -... ] ->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2) ->>> formset = LimitedFavoriteDrinkFormSet(initial=initial) ->>> for form in formset.forms: -... print form -<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name" /></td></tr> -<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" value="Bloody Mary" id="id_form-1-name" /></td></tr> - -# One form from initial and extra=3 with max_num=2 should result in the one -# initial form and one extra. - ->>> initial = [ -... {'name': 'Gin Tonic'}, -... ] ->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=2) ->>> formset = LimitedFavoriteDrinkFormSet(initial=initial) ->>> for form in formset.forms: -... print form -<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name" /></td></tr> -<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr> - - -# Regression test for #6926 ################################################## - -Make sure the management form has the correct prefix. - ->>> formset = FavoriteDrinksFormSet() ->>> formset.management_form.prefix -'form' - ->>> formset = FavoriteDrinksFormSet(data={}) ->>> formset.management_form.prefix -'form' - ->>> formset = FavoriteDrinksFormSet(initial={}) ->>> formset.management_form.prefix -'form' - -# Regression test for #12878 ################################################# - ->>> data = { -... 'drinks-TOTAL_FORMS': '2', # the number of forms rendered -... 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data -... 'drinks-MAX_NUM_FORMS': '0', # max number of forms -... 'drinks-0-name': 'Gin and Tonic', -... 'drinks-1-name': 'Gin and Tonic', -... } - ->>> formset = FavoriteDrinksFormSet(data, prefix='drinks') ->>> formset.is_valid() -False ->>> print formset.non_form_errors() -<ul class="errorlist"><li>You may only specify a drink once.</li></ul> - -""" - -data = { - 'choices-TOTAL_FORMS': '1', # the number of forms rendered - 'choices-INITIAL_FORMS': '0', # the number of forms with initial data - 'choices-MAX_NUM_FORMS': '0', # max number of forms - 'choices-0-choice': 'Calexico', - 'choices-0-votes': '100', -} - -class Choice(Form): - choice = CharField() - votes = IntegerField() - -ChoiceFormSet = formset_factory(Choice) - -class FormsetAsFooTests(TestCase): - def test_as_table(self): - formset = ChoiceFormSet(data, auto_id=False, prefix='choices') - self.assertEqual(formset.as_table(),"""<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> -<tr><th>Choice:</th><td><input type="text" name="choices-0-choice" value="Calexico" /></td></tr> -<tr><th>Votes:</th><td><input type="text" name="choices-0-votes" value="100" /></td></tr>""") - - def test_as_p(self): - formset = ChoiceFormSet(data, auto_id=False, prefix='choices') - self.assertEqual(formset.as_p(),"""<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> -<p>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></p> -<p>Votes: <input type="text" name="choices-0-votes" value="100" /></p>""") - - def test_as_ul(self): - formset = ChoiceFormSet(data, auto_id=False, prefix='choices') - self.assertEqual(formset.as_ul(),"""<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> -<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> -<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li>""") - diff --git a/tests/regressiontests/forms/localflavor/be.py b/tests/regressiontests/forms/localflavor/be.py index 8789d9f89d..2eefc59af9 100644 --- a/tests/regressiontests/forms/localflavor/be.py +++ b/tests/regressiontests/forms/localflavor/be.py @@ -51,7 +51,7 @@ class BETests(TestCase): self.assertEqual(u'0412.34.56.78', f.clean('0412.34.56.78')) self.assertEqual(u'012345678', f.clean('012345678')) self.assertEqual(u'0412345678', f.clean('0412345678')) - err_message = "[u'Enter a valid phone number in one of the formats 0x xxx xx xx, 0xx xx xx xx, 04xx xx xx xx, 0x/xxx.xx.xx, 0xx/xx.xx.xx, 04xx/xx.xx.xx, 0xxxxxxxx, 04xxxxxxxx, 0x.xxx.xx.xx, 0xx.xx.xx.xx, 04xx.xx.xx.xx.']" + err_message = "[u'Enter a valid phone number in one of the formats 0x xxx xx xx, 0xx xx xx xx, 04xx xx xx xx, 0x/xxx.xx.xx, 0xx/xx.xx.xx, 04xx/xx.xx.xx, 0x.xxx.xx.xx, 0xx.xx.xx.xx, 04xx.xx.xx.xx, 0xxxxxxxx or 04xxxxxxxx.']" self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '01234567') self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '12/345.67.89') self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '012/345.678.90') @@ -75,7 +75,7 @@ class BETests(TestCase): self.assertEqual(u'012345678', f.clean('012345678')) self.assertEqual(u'0412345678', f.clean('0412345678')) self.assertEqual(u'', f.clean('')) - err_message = "[u'Enter a valid phone number in one of the formats 0x xxx xx xx, 0xx xx xx xx, 04xx xx xx xx, 0x/xxx.xx.xx, 0xx/xx.xx.xx, 04xx/xx.xx.xx, 0xxxxxxxx, 04xxxxxxxx, 0x.xxx.xx.xx, 0xx.xx.xx.xx, 04xx.xx.xx.xx.']" + err_message = "[u'Enter a valid phone number in one of the formats 0x xxx xx xx, 0xx xx xx xx, 04xx xx xx xx, 0x/xxx.xx.xx, 0xx/xx.xx.xx, 04xx/xx.xx.xx, 0x.xxx.xx.xx, 0xx.xx.xx.xx, 04xx.xx.xx.xx, 0xxxxxxxx or 04xxxxxxxx.']" self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '01234567') self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '12/345.67.89') self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '012/345.678.90') @@ -85,10 +85,10 @@ class BETests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '012/34 56 789') self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '012.34 56 789') - def test_phone_number_field(self): + def test_region_field(self): w = BERegionSelect() self.assertEqual(u'<select name="regions">\n<option value="BRU">Brussels Capital Region</option>\n<option value="VLG" selected="selected">Flemish Region</option>\n<option value="WAL">Wallonia</option>\n</select>', w.render('regions', 'VLG')) - def test_phone_number_field(self): + def test_province_field(self): w = BEProvinceSelect() self.assertEqual(u'<select name="provinces">\n<option value="VAN">Antwerp</option>\n<option value="BRU">Brussels</option>\n<option value="VOV">East Flanders</option>\n<option value="VBR">Flemish Brabant</option>\n<option value="WHT">Hainaut</option>\n<option value="WLG" selected="selected">Liege</option>\n<option value="VLI">Limburg</option>\n<option value="WLX">Luxembourg</option>\n<option value="WNA">Namur</option>\n<option value="WBR">Walloon Brabant</option>\n<option value="VWV">West Flanders</option>\n</select>', w.render('provinces', 'WLG')) diff --git a/tests/regressiontests/forms/tests.py b/tests/regressiontests/forms/localflavortests.py similarity index 79% rename from tests/regressiontests/forms/tests.py rename to tests/regressiontests/forms/localflavortests.py index fbf3158ca1..30c06ef79a 100644 --- a/tests/regressiontests/forms/tests.py +++ b/tests/regressiontests/forms/localflavortests.py @@ -1,7 +1,4 @@ # -*- coding: utf-8 -*- -from extra import tests as extra_tests -from forms import tests as form_tests -from error_messages import tests as custom_error_message_tests from localflavor.ar import tests as localflavor_ar_tests from localflavor.at import tests as localflavor_at_tests from localflavor.au import tests as localflavor_au_tests @@ -32,25 +29,10 @@ from localflavor.uk import tests as localflavor_uk_tests from localflavor.us import tests as localflavor_us_tests from localflavor.uy import tests as localflavor_uy_tests from localflavor.za import tests as localflavor_za_tests -from regressions import tests as regression_tests -from util import tests as util_tests -from widgets import tests as widgets_tests -from formsets import tests as formset_tests -from media import media_tests - -from formsets import FormsetAsFooTests -from fields import FieldsTests -from validators import TestFieldWithValidators -from widgets import WidgetTests, ClearableFileInputTests from localflavor.be import BETests -from input_formats import * - __test__ = { - 'extra_tests': extra_tests, - 'form_tests': form_tests, - 'custom_error_message_tests': custom_error_message_tests, 'localflavor_ar_tests': localflavor_ar_tests, 'localflavor_at_tests': localflavor_at_tests, 'localflavor_au_tests': localflavor_au_tests, @@ -80,11 +62,6 @@ __test__ = { 'localflavor_us_tests': localflavor_us_tests, 'localflavor_uy_tests': localflavor_uy_tests, 'localflavor_za_tests': localflavor_za_tests, - 'regression_tests': regression_tests, - 'formset_tests': formset_tests, - 'media_tests': media_tests, - 'util_tests': util_tests, - 'widgets_tests': widgets_tests, } if __name__ == "__main__": diff --git a/tests/regressiontests/forms/media.py b/tests/regressiontests/forms/media.py deleted file mode 100644 index d715fb4d80..0000000000 --- a/tests/regressiontests/forms/media.py +++ /dev/null @@ -1,385 +0,0 @@ -# -*- coding: utf-8 -*- -# Tests for the media handling on widgets and forms - -media_tests = r""" ->>> from django.forms import TextInput, Media, TextInput, CharField, Form, MultiWidget ->>> from django.conf import settings ->>> ORIGINAL_MEDIA_URL = settings.MEDIA_URL ->>> settings.MEDIA_URL = 'http://media.example.com/media/' - -# Check construction of media objects ->>> m = Media(css={'all': ('path/to/css1','/path/to/css2')}, js=('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3')) ->>> print m -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> - ->>> class Foo: -... css = { -... 'all': ('path/to/css1','/path/to/css2') -... } -... js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') ->>> m3 = Media(Foo) ->>> print m3 -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> - ->>> m3 = Media(Foo) ->>> print m3 -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> - -# A widget can exist without a media definition ->>> class MyWidget(TextInput): -... pass - ->>> w = MyWidget() ->>> print w.media -<BLANKLINE> - -############################################################### -# DSL Class-based media definitions -############################################################### - -# A widget can define media if it needs to. -# Any absolute path will be preserved; relative paths are combined -# with the value of settings.MEDIA_URL ->>> class MyWidget1(TextInput): -... class Media: -... css = { -... 'all': ('path/to/css1','/path/to/css2') -... } -... js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') - ->>> w1 = MyWidget1() ->>> print w1.media -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> - -# Media objects can be interrogated by media type ->>> print w1.media['css'] -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> - ->>> print w1.media['js'] -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> - -# Media objects can be combined. Any given media resource will appear only -# once. Duplicated media definitions are ignored. ->>> class MyWidget2(TextInput): -... class Media: -... css = { -... 'all': ('/path/to/css2','/path/to/css3') -... } -... js = ('/path/to/js1','/path/to/js4') - ->>> class MyWidget3(TextInput): -... class Media: -... css = { -... 'all': ('/path/to/css3','path/to/css1') -... } -... js = ('/path/to/js1','/path/to/js4') - ->>> w2 = MyWidget2() ->>> w3 = MyWidget3() ->>> print w1.media + w2.media + w3.media -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/path/to/js4"></script> - -# Check that media addition hasn't affected the original objects ->>> print w1.media -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> - -# Regression check for #12879: specifying the same CSS or JS file -# multiple times in a single Media instance should result in that file -# only being included once. ->>> class MyWidget4(TextInput): -... class Media: -... css = {'all': ('/path/to/css1', '/path/to/css1')} -... js = ('/path/to/js1', '/path/to/js1') - ->>> w4 = MyWidget4() ->>> print w4.media -<link href="/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> - - -############################################################### -# Property-based media definitions -############################################################### - -# Widget media can be defined as a property ->>> class MyWidget4(TextInput): -... def _media(self): -... return Media(css={'all': ('/some/path',)}, js = ('/some/js',)) -... media = property(_media) - ->>> w4 = MyWidget4() ->>> print w4.media -<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/some/js"></script> - -# Media properties can reference the media of their parents ->>> class MyWidget5(MyWidget4): -... def _media(self): -... return super(MyWidget5, self).media + Media(css={'all': ('/other/path',)}, js = ('/other/js',)) -... media = property(_media) - ->>> w5 = MyWidget5() ->>> print w5.media -<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> -<link href="/other/path" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/some/js"></script> -<script type="text/javascript" src="/other/js"></script> - -# Media properties can reference the media of their parents, -# even if the parent media was defined using a class ->>> class MyWidget6(MyWidget1): -... def _media(self): -... return super(MyWidget6, self).media + Media(css={'all': ('/other/path',)}, js = ('/other/js',)) -... media = property(_media) - ->>> w6 = MyWidget6() ->>> print w6.media -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<link href="/other/path" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/other/js"></script> - -############################################################### -# Inheritance of media -############################################################### - -# If a widget extends another but provides no media definition, it inherits the parent widget's media ->>> class MyWidget7(MyWidget1): -... pass - ->>> w7 = MyWidget7() ->>> print w7.media -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> - -# If a widget extends another but defines media, it extends the parent widget's media by default ->>> class MyWidget8(MyWidget1): -... class Media: -... css = { -... 'all': ('/path/to/css3','path/to/css1') -... } -... js = ('/path/to/js1','/path/to/js4') - ->>> w8 = MyWidget8() ->>> print w8.media -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/path/to/js4"></script> - -# If a widget extends another but defines media, it extends the parents widget's media, -# even if the parent defined media using a property. ->>> class MyWidget9(MyWidget4): -... class Media: -... css = { -... 'all': ('/other/path',) -... } -... js = ('/other/js',) - ->>> w9 = MyWidget9() ->>> print w9.media -<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> -<link href="/other/path" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/some/js"></script> -<script type="text/javascript" src="/other/js"></script> - -# A widget can disable media inheritance by specifying 'extend=False' ->>> class MyWidget10(MyWidget1): -... class Media: -... extend = False -... css = { -... 'all': ('/path/to/css3','path/to/css1') -... } -... js = ('/path/to/js1','/path/to/js4') - ->>> w10 = MyWidget10() ->>> print w10.media -<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="/path/to/js4"></script> - -# A widget can explicitly enable full media inheritance by specifying 'extend=True' ->>> class MyWidget11(MyWidget1): -... class Media: -... extend = True -... css = { -... 'all': ('/path/to/css3','path/to/css1') -... } -... js = ('/path/to/js1','/path/to/js4') - ->>> w11 = MyWidget11() ->>> print w11.media -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/path/to/js4"></script> - -# A widget can enable inheritance of one media type by specifying extend as a tuple ->>> class MyWidget12(MyWidget1): -... class Media: -... extend = ('css',) -... css = { -... 'all': ('/path/to/css3','path/to/css1') -... } -... js = ('/path/to/js1','/path/to/js4') - ->>> w12 = MyWidget12() ->>> print w12.media -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="/path/to/js4"></script> - -############################################################### -# Multi-media handling for CSS -############################################################### - -# A widget can define CSS media for multiple output media types ->>> class MultimediaWidget(TextInput): -... class Media: -... css = { -... 'screen, print': ('/file1','/file2'), -... 'screen': ('/file3',), -... 'print': ('/file4',) -... } -... js = ('/path/to/js1','/path/to/js4') - ->>> multimedia = MultimediaWidget() ->>> print multimedia.media -<link href="/file4" type="text/css" media="print" rel="stylesheet" /> -<link href="/file3" type="text/css" media="screen" rel="stylesheet" /> -<link href="/file1" type="text/css" media="screen, print" rel="stylesheet" /> -<link href="/file2" type="text/css" media="screen, print" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="/path/to/js4"></script> - -############################################################### -# Multiwidget media handling -############################################################### - -# MultiWidgets have a default media definition that gets all the -# media from the component widgets ->>> class MyMultiWidget(MultiWidget): -... def __init__(self, attrs=None): -... widgets = [MyWidget1, MyWidget2, MyWidget3] -... super(MyMultiWidget, self).__init__(widgets, attrs) - ->>> mymulti = MyMultiWidget() ->>> print mymulti.media -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/path/to/js4"></script> - -############################################################### -# Media processing for forms -############################################################### - -# You can ask a form for the media required by its widgets. ->>> class MyForm(Form): -... field1 = CharField(max_length=20, widget=MyWidget1()) -... field2 = CharField(max_length=20, widget=MyWidget2()) ->>> f1 = MyForm() ->>> print f1.media -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/path/to/js4"></script> - -# Form media can be combined to produce a single media definition. ->>> class AnotherForm(Form): -... field3 = CharField(max_length=20, widget=MyWidget3()) ->>> f2 = AnotherForm() ->>> print f1.media + f2.media -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/path/to/js4"></script> - -# Forms can also define media, following the same rules as widgets. ->>> class FormWithMedia(Form): -... field1 = CharField(max_length=20, widget=MyWidget1()) -... field2 = CharField(max_length=20, widget=MyWidget2()) -... class Media: -... js = ('/some/form/javascript',) -... css = { -... 'all': ('/some/form/css',) -... } ->>> f3 = FormWithMedia() ->>> print f3.media -<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> -<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" /> -<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/path/to/js4"></script> -<script type="text/javascript" src="/some/form/javascript"></script> - -# Media works in templates ->>> from django.template import Template, Context ->>> Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})) -u'<script type="text/javascript" src="/path/to/js1"></script> -<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/path/to/js4"></script> -<script type="text/javascript" src="/some/form/javascript"></script><link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> -<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> -<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />' - ->>> settings.MEDIA_URL = ORIGINAL_MEDIA_URL -""" diff --git a/tests/regressiontests/forms/models.py b/tests/regressiontests/forms/models.py index a4891df06e..0a0fea45ad 100644 --- a/tests/regressiontests/forms/models.py +++ b/tests/regressiontests/forms/models.py @@ -1,14 +1,9 @@ # -*- coding: utf-8 -*- import datetime -import shutil import tempfile from django.db import models -# Can't import as "forms" due to implementation details in the test suite (the -# current file is called "forms" and is already imported). -from django import forms as django_forms from django.core.files.storage import FileSystemStorage -from django.test import TestCase temp_storage_location = tempfile.mkdtemp() temp_storage = FileSystemStorage(location=temp_storage_location) @@ -56,182 +51,11 @@ class ChoiceFieldModel(models.Model): multi_choice_int = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='multi_choice_int', default=lambda: [1]) -class ChoiceFieldForm(django_forms.ModelForm): - class Meta: - model = ChoiceFieldModel - class FileModel(models.Model): file = models.FileField(storage=temp_storage, upload_to='tests') -class FileForm(django_forms.Form): - file1 = django_forms.FileField() - class Group(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return u'%s' % self.name - -class TestTicket12510(TestCase): - ''' It is not necessary to generate choices for ModelChoiceField (regression test for #12510). ''' - def setUp(self): - self.groups = [Group.objects.create(name=name) for name in 'abc'] - - def test_choices_not_fetched_when_not_rendering(self): - def test(): - field = django_forms.ModelChoiceField(Group.objects.order_by('-name')) - self.assertEqual('a', field.clean(self.groups[0].pk).name) - # only one query is required to pull the model from DB - self.assertNumQueries(1, test) - -class ModelFormCallableModelDefault(TestCase): - def test_no_empty_option(self): - "If a model's ForeignKey has blank=False and a default, no empty option is created (Refs #10792)." - option = ChoiceOptionModel.objects.create(name='default') - - choices = list(ChoiceFieldForm().fields['choice'].choices) - self.assertEquals(len(choices), 1) - self.assertEquals(choices[0], (option.pk, unicode(option))) - - def test_callable_initial_value(self): - "The initial value for a callable default returning a queryset is the pk (refs #13769)" - obj1 = ChoiceOptionModel.objects.create(id=1, name='default') - obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2') - obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3') - self.assertEquals(ChoiceFieldForm().as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice"> -<option value="1" selected="selected">ChoiceOption 1</option> -<option value="2">ChoiceOption 2</option> -<option value="3">ChoiceOption 3</option> -</select><input type="hidden" name="initial-choice" value="1" id="initial-id_choice" /></p> -<p><label for="id_choice_int">Choice int:</label> <select name="choice_int" id="id_choice_int"> -<option value="1" selected="selected">ChoiceOption 1</option> -<option value="2">ChoiceOption 2</option> -<option value="3">ChoiceOption 3</option> -</select><input type="hidden" name="initial-choice_int" value="1" id="initial-id_choice_int" /></p> -<p><label for="id_multi_choice">Multi choice:</label> <select multiple="multiple" name="multi_choice" id="id_multi_choice"> -<option value="1" selected="selected">ChoiceOption 1</option> -<option value="2">ChoiceOption 2</option> -<option value="3">ChoiceOption 3</option> -</select><input type="hidden" name="initial-multi_choice" value="1" id="initial-id_multi_choice_0" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p> -<p><label for="id_multi_choice_int">Multi choice int:</label> <select multiple="multiple" name="multi_choice_int" id="id_multi_choice_int"> -<option value="1" selected="selected">ChoiceOption 1</option> -<option value="2">ChoiceOption 2</option> -<option value="3">ChoiceOption 3</option> -</select><input type="hidden" name="initial-multi_choice_int" value="1" id="initial-id_multi_choice_int_0" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p>""") - - def test_initial_instance_value(self): - "Initial instances for model fields may also be instances (refs #7287)" - obj1 = ChoiceOptionModel.objects.create(id=1, name='default') - obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2') - obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3') - self.assertEquals(ChoiceFieldForm(initial={ - 'choice': obj2, - 'choice_int': obj2, - 'multi_choice': [obj2,obj3], - 'multi_choice_int': ChoiceOptionModel.objects.exclude(name="default"), - }).as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice"> -<option value="1">ChoiceOption 1</option> -<option value="2" selected="selected">ChoiceOption 2</option> -<option value="3">ChoiceOption 3</option> -</select><input type="hidden" name="initial-choice" value="2" id="initial-id_choice" /></p> -<p><label for="id_choice_int">Choice int:</label> <select name="choice_int" id="id_choice_int"> -<option value="1">ChoiceOption 1</option> -<option value="2" selected="selected">ChoiceOption 2</option> -<option value="3">ChoiceOption 3</option> -</select><input type="hidden" name="initial-choice_int" value="2" id="initial-id_choice_int" /></p> -<p><label for="id_multi_choice">Multi choice:</label> <select multiple="multiple" name="multi_choice" id="id_multi_choice"> -<option value="1">ChoiceOption 1</option> -<option value="2" selected="selected">ChoiceOption 2</option> -<option value="3" selected="selected">ChoiceOption 3</option> -</select><input type="hidden" name="initial-multi_choice" value="2" id="initial-id_multi_choice_0" /> -<input type="hidden" name="initial-multi_choice" value="3" id="initial-id_multi_choice_1" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p> -<p><label for="id_multi_choice_int">Multi choice int:</label> <select multiple="multiple" name="multi_choice_int" id="id_multi_choice_int"> -<option value="1">ChoiceOption 1</option> -<option value="2" selected="selected">ChoiceOption 2</option> -<option value="3" selected="selected">ChoiceOption 3</option> -</select><input type="hidden" name="initial-multi_choice_int" value="2" id="initial-id_multi_choice_int_0" /> -<input type="hidden" name="initial-multi_choice_int" value="3" id="initial-id_multi_choice_int_1" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p>""") - - -__test__ = {'API_TESTS': """ ->>> from django.forms.models import ModelForm ->>> from django.core.files.uploadedfile import SimpleUploadedFile - -# FileModel with unicode filename and data ######################### ->>> f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')}, auto_id=False) ->>> f.is_valid() -True ->>> f.cleaned_data -{'file1': <SimpleUploadedFile: 我隻氣墊船裝滿晒鱔.txt (text/plain)>} ->>> m = FileModel.objects.create(file=f.cleaned_data['file1']) - -# It's enough that m gets created without error. Preservation of the exotic name is checked -# in a file_uploads test; it's hard to do that correctly with doctest's unicode issues. So -# we create and then immediately delete m so as to not leave the exotically named file around -# for shutil.rmtree (on Windows) to have trouble with later. ->>> m.delete() - -# Boundary conditions on a PostitiveIntegerField ######################### ->>> class BoundaryForm(ModelForm): -... class Meta: -... model = BoundaryModel ->>> f = BoundaryForm({'positive_integer': 100}) ->>> f.is_valid() -True ->>> f = BoundaryForm({'positive_integer': 0}) ->>> f.is_valid() -True ->>> f = BoundaryForm({'positive_integer': -100}) ->>> f.is_valid() -False - -# Formfield initial values ######## -If the model has default values for some fields, they are used as the formfield -initial values. ->>> class DefaultsForm(ModelForm): -... class Meta: -... model = Defaults ->>> DefaultsForm().fields['name'].initial -u'class default value' ->>> DefaultsForm().fields['def_date'].initial -datetime.date(1980, 1, 1) ->>> DefaultsForm().fields['value'].initial -42 ->>> r1 = DefaultsForm()['callable_default'].as_widget() ->>> r2 = DefaultsForm()['callable_default'].as_widget() ->>> r1 == r2 -False - -In a ModelForm that is passed an instance, the initial values come from the -instance's values, not the model's defaults. ->>> foo_instance = Defaults(name=u'instance value', def_date=datetime.date(1969, 4, 4), value=12) ->>> instance_form = DefaultsForm(instance=foo_instance) ->>> instance_form.initial['name'] -u'instance value' ->>> instance_form.initial['def_date'] -datetime.date(1969, 4, 4) ->>> instance_form.initial['value'] -12 - ->>> from django.forms import CharField ->>> class ExcludingForm(ModelForm): -... name = CharField(max_length=255) -... class Meta: -... model = Defaults -... exclude = ['name', 'callable_default'] ->>> f = ExcludingForm({'name': u'Hello', 'value': 99, 'def_date': datetime.date(1999, 3, 2)}) ->>> f.is_valid() -True ->>> f.cleaned_data['name'] -u'Hello' ->>> obj = f.save() ->>> obj.name -u'class default value' ->>> obj.value -99 ->>> obj.def_date -datetime.date(1999, 3, 2) ->>> shutil.rmtree(temp_storage_location) - - -"""} diff --git a/tests/regressiontests/forms/regressions.py b/tests/regressiontests/forms/regressions.py deleted file mode 100644 index 9471932057..0000000000 --- a/tests/regressiontests/forms/regressions.py +++ /dev/null @@ -1,135 +0,0 @@ -# -*- coding: utf-8 -*- -# Tests to prevent against recurrences of earlier bugs. - -tests = r""" -It should be possible to re-use attribute dictionaries (#3810) ->>> from django.forms import * ->>> extra_attrs = {'class': 'special'} ->>> class TestForm(Form): -... f1 = CharField(max_length=10, widget=TextInput(attrs=extra_attrs)) -... f2 = CharField(widget=TextInput(attrs=extra_attrs)) ->>> TestForm(auto_id=False).as_p() -u'<p>F1: <input type="text" class="special" name="f1" maxlength="10" /></p>\n<p>F2: <input type="text" class="special" name="f2" /></p>' - -####################### -# Tests for form i18n # -####################### -There were some problems with form translations in #3600 - ->>> from django.utils.translation import ugettext_lazy, activate, deactivate ->>> class SomeForm(Form): -... username = CharField(max_length=10, label=ugettext_lazy('Username')) ->>> f = SomeForm() ->>> print f.as_p() -<p><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p> - -Translations are done at rendering time, so multi-lingual apps can define forms -early and still send back the right translation. - ->>> activate('de') ->>> print f.as_p() -<p><label for="id_username">Benutzername:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p> ->>> activate('pl') ->>> f.as_p() -u'<p><label for="id_username">Nazwa u\u017cytkownika:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>' ->>> deactivate() - -There was some problems with form translations in #5216 ->>> class SomeForm(Form): -... field_1 = CharField(max_length=10, label=ugettext_lazy('field_1')) -... field_2 = CharField(max_length=10, label=ugettext_lazy('field_2'), widget=TextInput(attrs={'id': 'field_2_id'})) ->>> f = SomeForm() ->>> print f['field_1'].label_tag() -<label for="id_field_1">field_1</label> ->>> print f['field_2'].label_tag() -<label for="field_2_id">field_2</label> - -Unicode decoding problems... ->>> GENDERS = ((u'\xc5', u'En tied\xe4'), (u'\xf8', u'Mies'), (u'\xdf', u'Nainen')) ->>> class SomeForm(Form): -... somechoice = ChoiceField(choices=GENDERS, widget=RadioSelect(), label=u'\xc5\xf8\xdf') ->>> f = SomeForm() ->>> f.as_p() -u'<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>' - -Testing choice validation with UTF-8 bytestrings as input (these are the -Russian abbreviations "мес." and "шт.". - ->>> UNITS = (('\xd0\xbc\xd0\xb5\xd1\x81.', '\xd0\xbc\xd0\xb5\xd1\x81.'), ('\xd1\x88\xd1\x82.', '\xd1\x88\xd1\x82.')) ->>> f = ChoiceField(choices=UNITS) ->>> f.clean(u'\u0448\u0442.') -u'\u0448\u0442.' ->>> f.clean('\xd1\x88\xd1\x82.') -u'\u0448\u0442.' - -Translated error messages used to be buggy. ->>> activate('ru') ->>> f = SomeForm({}) ->>> f.as_p() -u'<ul class="errorlist"><li>\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>' ->>> deactivate() - -Deep copying translated text shouldn't raise an error ->>> from django.utils.translation import gettext_lazy ->>> class CopyForm(Form): -... degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),))) ->>> f = CopyForm() - -####################### -# Miscellaneous Tests # -####################### - -There once was a problem with Form fields called "data". Let's make sure that -doesn't come back. ->>> class DataForm(Form): -... data = CharField(max_length=10) ->>> f = DataForm({'data': 'xyzzy'}) ->>> f.is_valid() -True ->>> f.cleaned_data -{'data': u'xyzzy'} - -A form with *only* hidden fields that has errors is going to be very unusual. -But we can try to make sure it doesn't generate invalid XHTML. In this case, -the as_p() method is the tricky one, since error lists cannot be nested -(validly) inside p elements. - ->>> class HiddenForm(Form): -... data = IntegerField(widget=HiddenInput) ->>> f = HiddenForm({}) ->>> f.as_p() -u'<ul class="errorlist"><li>(Hidden field data) This field is required.</li></ul>\n<p> <input type="hidden" name="data" id="id_data" /></p>' ->>> f.as_table() -u'<tr><td colspan="2"><ul class="errorlist"><li>(Hidden field data) This field is required.</li></ul><input type="hidden" name="data" id="id_data" /></td></tr>' - -################################################### -# Tests for XSS vulnerabilities in error messages # -################################################### - -# The forms layer doesn't escape input values directly because error messages -# might be presented in non-HTML contexts. Instead, the message is just marked -# for escaping by the template engine. So we'll need to construct a little -# silly template to trigger the escaping. - ->>> from django.template import Template, Context ->>> t = Template('{{ form.errors }}') - ->>> class SomeForm(Form): -... field = ChoiceField(choices=[('one', 'One')]) ->>> f = SomeForm({'field': '<script>'}) ->>> t.render(Context({'form': f})) -u'<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. <script> is not one of the available choices.</li></ul></li></ul>' - ->>> class SomeForm(Form): -... field = MultipleChoiceField(choices=[('one', 'One')]) ->>> f = SomeForm({'field': ['<script>']}) ->>> t.render(Context({'form': f})) -u'<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. <script> is not one of the available choices.</li></ul></li></ul>' - ->>> from regressiontests.forms.models import ChoiceModel ->>> class SomeForm(Form): -... field = ModelMultipleChoiceField(ChoiceModel.objects.all()) ->>> f = SomeForm({'field': ['<script>']}) ->>> t.render(Context({'form': f})) -u'<ul class="errorlist"><li>field<ul class="errorlist"><li>"<script>" is not a valid value for a primary key.</li></ul></li></ul>' -""" diff --git a/tests/regressiontests/forms/tests/__init__.py b/tests/regressiontests/forms/tests/__init__.py new file mode 100644 index 0000000000..0e2df05488 --- /dev/null +++ b/tests/regressiontests/forms/tests/__init__.py @@ -0,0 +1,15 @@ +from error_messages import * +from extra import * +from fields import FieldsTests +from forms import * +from formsets import * +from input_formats import * +from media import * +from models import * +from regressions import * +from util import * +from validators import TestFieldWithValidators +from widgets import * + +from regressiontests.forms.localflavortests import __test__ +from regressiontests.forms.localflavortests import BETests, IsraelLocalFlavorTests diff --git a/tests/regressiontests/forms/tests/error_messages.py b/tests/regressiontests/forms/tests/error_messages.py new file mode 100644 index 0000000000..a9f4f37a8d --- /dev/null +++ b/tests/regressiontests/forms/tests/error_messages.py @@ -0,0 +1,253 @@ +# -*- coding: utf-8 -*- +from django.core.files.uploadedfile import SimpleUploadedFile +from django.forms import * +from django.test import TestCase +from django.utils.safestring import mark_safe +from django.utils import unittest + +class AssertFormErrorsMixin(object): + def assertFormErrors(self, expected, the_callable, *args, **kwargs): + try: + the_callable(*args, **kwargs) + self.fail("Testing the 'clean' method on %s failed to raise a ValidationError.") + except ValidationError, e: + self.assertEqual(e.messages, expected) + + +class FormsErrorMessagesTestCase(unittest.TestCase, AssertFormErrorsMixin): + def test_charfield(self): + e = { + 'required': 'REQUIRED', + 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s', + 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', + } + f = CharField(min_length=5, max_length=10, error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'LENGTH 4, MIN LENGTH 5'], f.clean, '1234') + self.assertFormErrors([u'LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901') + + def test_integerfield(self): + e = { + 'required': 'REQUIRED', + 'invalid': 'INVALID', + 'min_value': 'MIN VALUE IS %(limit_value)s', + 'max_value': 'MAX VALUE IS %(limit_value)s', + } + f = IntegerField(min_value=5, max_value=10, error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'INVALID'], f.clean, 'abc') + self.assertFormErrors([u'MIN VALUE IS 5'], f.clean, '4') + self.assertFormErrors([u'MAX VALUE IS 10'], f.clean, '11') + + def test_floatfield(self): + e = { + 'required': 'REQUIRED', + 'invalid': 'INVALID', + 'min_value': 'MIN VALUE IS %(limit_value)s', + 'max_value': 'MAX VALUE IS %(limit_value)s', + } + f = FloatField(min_value=5, max_value=10, error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'INVALID'], f.clean, 'abc') + self.assertFormErrors([u'MIN VALUE IS 5'], f.clean, '4') + self.assertFormErrors([u'MAX VALUE IS 10'], f.clean, '11') + + def test_decimalfield(self): + e = { + 'required': 'REQUIRED', + 'invalid': 'INVALID', + 'min_value': 'MIN VALUE IS %(limit_value)s', + 'max_value': 'MAX VALUE IS %(limit_value)s', + 'max_digits': 'MAX DIGITS IS %s', + 'max_decimal_places': 'MAX DP IS %s', + 'max_whole_digits': 'MAX DIGITS BEFORE DP IS %s', + } + f = DecimalField(min_value=5, max_value=10, error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'INVALID'], f.clean, 'abc') + self.assertFormErrors([u'MIN VALUE IS 5'], f.clean, '4') + self.assertFormErrors([u'MAX VALUE IS 10'], f.clean, '11') + + f2 = DecimalField(max_digits=4, decimal_places=2, error_messages=e) + self.assertFormErrors([u'MAX DIGITS IS 4'], f2.clean, '123.45') + self.assertFormErrors([u'MAX DP IS 2'], f2.clean, '1.234') + self.assertFormErrors([u'MAX DIGITS BEFORE DP IS 2'], f2.clean, '123.4') + + def test_datefield(self): + e = { + 'required': 'REQUIRED', + 'invalid': 'INVALID', + } + f = DateField(error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'INVALID'], f.clean, 'abc') + + def test_timefield(self): + e = { + 'required': 'REQUIRED', + 'invalid': 'INVALID', + } + f = TimeField(error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'INVALID'], f.clean, 'abc') + + def test_datetimefield(self): + e = { + 'required': 'REQUIRED', + 'invalid': 'INVALID', + } + f = DateTimeField(error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'INVALID'], f.clean, 'abc') + + def test_regexfield(self): + e = { + 'required': 'REQUIRED', + 'invalid': 'INVALID', + 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s', + 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', + } + f = RegexField(r'^\d+$', min_length=5, max_length=10, error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'INVALID'], f.clean, 'abcde') + self.assertFormErrors([u'LENGTH 4, MIN LENGTH 5'], f.clean, '1234') + self.assertFormErrors([u'LENGTH 11, MAX LENGTH 10'], f.clean, '12345678901') + + def test_emailfield(self): + e = { + 'required': 'REQUIRED', + 'invalid': 'INVALID', + 'min_length': 'LENGTH %(show_value)s, MIN LENGTH %(limit_value)s', + 'max_length': 'LENGTH %(show_value)s, MAX LENGTH %(limit_value)s', + } + f = EmailField(min_length=8, max_length=10, error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'INVALID'], f.clean, 'abcdefgh') + self.assertFormErrors([u'LENGTH 7, MIN LENGTH 8'], f.clean, 'a@b.com') + self.assertFormErrors([u'LENGTH 11, MAX LENGTH 10'], f.clean, 'aye@bee.com') + + def test_filefield(self): + e = { + 'required': 'REQUIRED', + 'invalid': 'INVALID', + 'missing': 'MISSING', + 'empty': 'EMPTY FILE', + } + f = FileField(error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'INVALID'], f.clean, 'abc') + self.assertFormErrors([u'EMPTY FILE'], f.clean, SimpleUploadedFile('name', None)) + self.assertFormErrors([u'EMPTY FILE'], f.clean, SimpleUploadedFile('name', '')) + + def test_urlfield(self): + e = { + 'required': 'REQUIRED', + 'invalid': 'INVALID', + 'invalid_link': 'INVALID LINK', + } + f = URLField(verify_exists=True, error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'INVALID'], f.clean, 'abc.c') + self.assertFormErrors([u'INVALID LINK'], f.clean, 'http://www.broken.djangoproject.com') + + def test_booleanfield(self): + e = { + 'required': 'REQUIRED', + } + f = BooleanField(error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + + def test_choicefield(self): + e = { + 'required': 'REQUIRED', + 'invalid_choice': '%(value)s IS INVALID CHOICE', + } + f = ChoiceField(choices=[('a', 'aye')], error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'b IS INVALID CHOICE'], f.clean, 'b') + + def test_multiplechoicefield(self): + e = { + 'required': 'REQUIRED', + 'invalid_choice': '%(value)s IS INVALID CHOICE', + 'invalid_list': 'NOT A LIST', + } + f = MultipleChoiceField(choices=[('a', 'aye')], error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'NOT A LIST'], f.clean, 'b') + self.assertFormErrors([u'b IS INVALID CHOICE'], f.clean, ['b']) + + def test_splitdatetimefield(self): + e = { + 'required': 'REQUIRED', + 'invalid_date': 'INVALID DATE', + 'invalid_time': 'INVALID TIME', + } + f = SplitDateTimeField(error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'INVALID DATE', u'INVALID TIME'], f.clean, ['a', 'b']) + + def test_ipaddressfield(self): + e = { + 'required': 'REQUIRED', + 'invalid': 'INVALID IP ADDRESS', + } + f = IPAddressField(error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'INVALID IP ADDRESS'], f.clean, '127.0.0') + + def test_subclassing_errorlist(self): + class TestForm(Form): + first_name = CharField() + last_name = CharField() + birthday = DateField() + + def clean(self): + raise ValidationError("I like to be awkward.") + + class CustomErrorList(util.ErrorList): + def __unicode__(self): + return self.as_divs() + + def as_divs(self): + if not self: return u'' + return mark_safe(u'<div class="error">%s</div>' % ''.join([u'<p>%s</p>' % e for e in self])) + + # This form should print errors the default way. + form1 = TestForm({'first_name': 'John'}) + self.assertEqual(str(form1['last_name'].errors), '<ul class="errorlist"><li>This field is required.</li></ul>') + self.assertEqual(str(form1.errors['__all__']), '<ul class="errorlist"><li>I like to be awkward.</li></ul>') + + # This one should wrap error groups in the customized way. + form2 = TestForm({'first_name': 'John'}, error_class=CustomErrorList) + self.assertEqual(str(form2['last_name'].errors), '<div class="error"><p>This field is required.</p></div>') + self.assertEqual(str(form2.errors['__all__']), '<div class="error"><p>I like to be awkward.</p></div>') + + +class ModelChoiceFieldErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): + def test_modelchoicefield(self): + # Create choices for the model choice field tests below. + from regressiontests.forms.models import ChoiceModel + c1 = ChoiceModel.objects.create(pk=1, name='a') + c2 = ChoiceModel.objects.create(pk=2, name='b') + c3 = ChoiceModel.objects.create(pk=3, name='c') + + # ModelChoiceField + e = { + 'required': 'REQUIRED', + 'invalid_choice': 'INVALID CHOICE', + } + f = ModelChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'INVALID CHOICE'], f.clean, '4') + + # ModelMultipleChoiceField + e = { + 'required': 'REQUIRED', + 'invalid_choice': '%s IS INVALID CHOICE', + 'list': 'NOT A LIST OF VALUES', + } + f = ModelMultipleChoiceField(queryset=ChoiceModel.objects.all(), error_messages=e) + self.assertFormErrors([u'REQUIRED'], f.clean, '') + self.assertFormErrors([u'NOT A LIST OF VALUES'], f.clean, '3') + self.assertFormErrors([u'4 IS INVALID CHOICE'], f.clean, ['4']) diff --git a/tests/regressiontests/forms/extra.py b/tests/regressiontests/forms/tests/extra.py similarity index 54% rename from tests/regressiontests/forms/extra.py rename to tests/regressiontests/forms/tests/extra.py index 57e8e91a60..54f35ee62e 100644 --- a/tests/regressiontests/forms/extra.py +++ b/tests/regressiontests/forms/tests/extra.py @@ -1,25 +1,29 @@ # -*- coding: utf-8 -*- -tests = r""" ->>> from django.forms import * ->>> from django.utils.encoding import force_unicode ->>> import datetime ->>> import time ->>> import re ->>> from decimal import Decimal +import datetime +from decimal import Decimal +import re +import time +from django.conf import settings +from django.forms import * +from django.forms.extras import SelectDateWidget +from django.forms.util import ErrorList +from django.test import TestCase +from django.utils import translation +from django.utils import unittest +from django.utils.encoding import force_unicode +from django.utils.encoding import smart_unicode +from error_messages import AssertFormErrorsMixin -############### -# Extra stuff # -############### -The forms library comes with some extra, higher-level Field and Widget -classes that demonstrate some of the library's abilities. +class FormsExtraTestCase(unittest.TestCase, AssertFormErrorsMixin): + ############### + # Extra stuff # + ############### -# SelectDateWidget ############################################################ - ->>> from django.forms.extras import SelectDateWidget ->>> w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016')) ->>> print w.render('mydate', '') -<select name="mydate_month" id="id_mydate_month"> + # The forms library comes with some extra, higher-level Field and Widget + def test_selectdate(self): + w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016')) + self.assertEqual(w.render('mydate', ''), """<select name="mydate_month" id="id_mydate_month"> <option value="0">---</option> <option value="1">January</option> <option value="2">February</option> @@ -80,11 +84,10 @@ classes that demonstrate some of the library's abilities. <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> -</select> ->>> w.render('mydate', None) == w.render('mydate', '') -True ->>> print w.render('mydate', '2010-04-15') -<select name="mydate_month" id="id_mydate_month"> +</select>""") + self.assertEqual(w.render('mydate', None), w.render('mydate', '')) + + self.assertEqual(w.render('mydate', '2010-04-15'), """<select name="mydate_month" id="id_mydate_month"> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> @@ -142,16 +145,13 @@ True <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> -</select> +</select>""") -Accepts a datetime or a string: + # Accepts a datetime or a string: + self.assertEqual(w.render('mydate', datetime.date(2010, 4, 15)), w.render('mydate', '2010-04-15')) ->>> w.render('mydate', datetime.date(2010, 4, 15)) == w.render('mydate', '2010-04-15') -True - -Invalid dates still render the failed date: ->>> print w.render('mydate', '2010-02-31') -<select name="mydate_month" id="id_mydate_month"> + # Invalid dates still render the failed date: + self.assertEqual(w.render('mydate', '2010-02-31'), """<select name="mydate_month" id="id_mydate_month"> <option value="1">January</option> <option value="2" selected="selected">February</option> <option value="3">March</option> @@ -209,13 +209,11 @@ Invalid dates still render the failed date: <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> -</select> +</select>""") -Using a SelectDateWidget in a form: - ->>> w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016'), required=False) ->>> print w.render('mydate', '') -<select name="mydate_month" id="id_mydate_month"> + # Using a SelectDateWidget in a form: + w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016'), required=False) + self.assertEqual(w.render('mydate', ''), """<select name="mydate_month" id="id_mydate_month"> <option value="0">---</option> <option value="1">January</option> <option value="2">February</option> @@ -276,9 +274,8 @@ Using a SelectDateWidget in a form: <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> -</select> ->>> print w.render('mydate', '2010-04-15') -<select name="mydate_month" id="id_mydate_month"> +</select>""") + self.assertEqual(w.render('mydate', '2010-04-15'), """<select name="mydate_month" id="id_mydate_month"> <option value="0">---</option> <option value="1">January</option> <option value="2">February</option> @@ -339,40 +336,213 @@ Using a SelectDateWidget in a form: <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> +</select>""") + + class GetDate(Form): + mydate = DateField(widget=SelectDateWidget) + + a = GetDate({'mydate_month':'4', 'mydate_day':'1', 'mydate_year':'2008'}) + self.assertTrue(a.is_valid()) + self.assertEqual(a.cleaned_data['mydate'], datetime.date(2008, 4, 1)) + + # As with any widget that implements get_value_from_datadict, + # we must be prepared to accept the input from the "as_hidden" + # rendering as well. + + self.assertEqual(a['mydate'].as_hidden(), '<input type="hidden" name="mydate" value="2008-4-1" id="id_mydate" />') + + b = GetDate({'mydate':'2008-4-1'}) + self.assertTrue(b.is_valid()) + self.assertEqual(b.cleaned_data['mydate'], datetime.date(2008, 4, 1)) + + def test_multiwidget(self): + # MultiWidget and MultiValueField ############################################# + # MultiWidgets are widgets composed of other widgets. They are usually + # combined with MultiValueFields - a field that is composed of other fields. + # MulitWidgets can themselved be composed of other MultiWidgets. + # SplitDateTimeWidget is one example of a MultiWidget. + + class ComplexMultiWidget(MultiWidget): + def __init__(self, attrs=None): + widgets = ( + TextInput(), + SelectMultiple(choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), + SplitDateTimeWidget(), + ) + super(ComplexMultiWidget, self).__init__(widgets, attrs) + + def decompress(self, value): + if value: + data = value.split(',') + return [data[0], data[1], datetime.datetime(*time.strptime(data[2], "%Y-%m-%d %H:%M:%S")[0:6])] + return [None, None, None] + + def format_output(self, rendered_widgets): + return u'\n'.join(rendered_widgets) + + w = ComplexMultiWidget() + self.assertEqual(w.render('name', 'some text,JP,2007-04-25 06:24:00'), """<input type="text" name="name_0" value="some text" /> +<select multiple="multiple" name="name_1"> +<option value="J" selected="selected">John</option> +<option value="P" selected="selected">Paul</option> +<option value="G">George</option> +<option value="R">Ringo</option> </select> ->>> class GetDate(Form): -... mydate = DateField(widget=SelectDateWidget) ->>> a = GetDate({'mydate_month':'4', 'mydate_day':'1', 'mydate_year':'2008'}) ->>> print a.is_valid() -True ->>> print a.cleaned_data['mydate'] -2008-04-01 +<input type="text" name="name_2_0" value="2007-04-25" /><input type="text" name="name_2_1" value="06:24:00" />""") -As with any widget that implements get_value_from_datadict, -we must be prepared to accept the input from the "as_hidden" -rendering as well. + class ComplexField(MultiValueField): + def __init__(self, required=True, widget=None, label=None, initial=None): + fields = ( + CharField(), + MultipleChoiceField(choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), + SplitDateTimeField() + ) + super(ComplexField, self).__init__(fields, required, widget, label, initial) ->>> print a['mydate'].as_hidden() -<input type="hidden" name="mydate" value="2008-4-1" id="id_mydate" /> ->>> b=GetDate({'mydate':'2008-4-1'}) ->>> print b.is_valid() -True ->>> print b.cleaned_data['mydate'] -2008-04-01 + def compress(self, data_list): + if data_list: + return '%s,%s,%s' % (data_list[0],''.join(data_list[1]),data_list[2]) + return None + + f = ComplexField(widget=w) + self.assertEqual(f.clean(['some text', ['J','P'], ['2007-04-25','6:24:00']]), u'some text,JP,2007-04-25 06:24:00') + self.assertFormErrors([u'Select a valid choice. X is not one of the available choices.'], f.clean, ['some text',['X'], ['2007-04-25','6:24:00']]) + + # If insufficient data is provided, None is substituted + self.assertFormErrors([u'This field is required.'], f.clean, ['some text',['JP']]) + + class ComplexFieldForm(Form): + field1 = ComplexField(widget=w) + + f = ComplexFieldForm() + self.assertEqual(f.as_table(), """<tr><th><label for="id_field1_0">Field1:</label></th><td><input type="text" name="field1_0" id="id_field1_0" /> +<select multiple="multiple" name="field1_1" id="id_field1_1"> +<option value="J">John</option> +<option value="P">Paul</option> +<option value="G">George</option> +<option value="R">Ringo</option> +</select> +<input type="text" name="field1_2_0" id="id_field1_2_0" /><input type="text" name="field1_2_1" id="id_field1_2_1" /></td></tr>""") + + f = ComplexFieldForm({'field1_0':'some text','field1_1':['J','P'], 'field1_2_0':'2007-04-25', 'field1_2_1':'06:24:00'}) + self.assertEqual(f.as_table(), """<tr><th><label for="id_field1_0">Field1:</label></th><td><input type="text" name="field1_0" value="some text" id="id_field1_0" /> +<select multiple="multiple" name="field1_1" id="id_field1_1"> +<option value="J" selected="selected">John</option> +<option value="P" selected="selected">Paul</option> +<option value="G">George</option> +<option value="R">Ringo</option> +</select> +<input type="text" name="field1_2_0" value="2007-04-25" id="id_field1_2_0" /><input type="text" name="field1_2_1" value="06:24:00" id="id_field1_2_1" /></td></tr>""") + + self.assertEqual(f.cleaned_data['field1'], u'some text,JP,2007-04-25 06:24:00') + + def test_ipaddress(self): + f = IPAddressField() + self.assertFormErrors([u'This field is required.'], f.clean, '') + self.assertFormErrors([u'This field is required.'], f.clean, None) + self.assertEqual(f.clean('127.0.0.1'), u'127.0.0.1') + self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, 'foo') + self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '127.0.0.') + self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5') + self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '256.125.1.5') + + f = IPAddressField(required=False) + self.assertEqual(f.clean(''), u'') + self.assertEqual(f.clean(None), u'') + self.assertEqual(f.clean('127.0.0.1'), u'127.0.0.1') + self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, 'foo') + self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '127.0.0.') + self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5') + self.assertFormErrors([u'Enter a valid IPv4 address.'], f.clean, '256.125.1.5') + + def test_smart_unicode(self): + class Test: + def __str__(self): + return 'ŠĐĆŽćžšđ' + + class TestU: + def __str__(self): + return 'Foo' + def __unicode__(self): + return u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111' + + self.assertEqual(smart_unicode(Test()), u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') + self.assertEqual(smart_unicode(TestU()), u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') + self.assertEqual(smart_unicode(1), u'1') + self.assertEqual(smart_unicode('foo'), u'foo') + + def test_accessing_clean(self): + class UserForm(Form): + username = CharField(max_length=10) + password = CharField(widget=PasswordInput) + + def clean(self): + data = self.cleaned_data + + if not self.errors: + data['username'] = data['username'].lower() + + return data + + f = UserForm({'username': 'SirRobin', 'password': 'blue'}) + self.assertTrue(f.is_valid()) + self.assertEqual(f.cleaned_data['username'], u'sirrobin') + + def test_overriding_errorlist(self): + class DivErrorList(ErrorList): + def __unicode__(self): + return self.as_divs() + + def as_divs(self): + if not self: return u'' + return u'<div class="errorlist">%s</div>' % ''.join([u'<div class="error">%s</div>' % force_unicode(e) for e in self]) + + class CommentForm(Form): + name = CharField(max_length=50, required=False) + email = EmailField() + comment = CharField() + + data = dict(email='invalid') + f = CommentForm(data, auto_id=False, error_class=DivErrorList) + self.assertEqual(f.as_p(), """<p>Name: <input type="text" name="name" maxlength="50" /></p> +<div class="errorlist"><div class="error">Enter a valid e-mail address.</div></div> +<p>Email: <input type="text" name="email" value="invalid" /></p> +<div class="errorlist"><div class="error">This field is required.</div></div> +<p>Comment: <input type="text" name="comment" /></p>""") + + def test_multipart_encoded_form(self): + class FormWithoutFile(Form): + username = CharField() + + class FormWithFile(Form): + username = CharField() + file = FileField() + + class FormWithImage(Form): + image = ImageField() + + self.assertFalse(FormWithoutFile().is_multipart()) + self.assertTrue(FormWithFile().is_multipart()) + self.assertTrue(FormWithImage().is_multipart()) -USE_L10N tests +class FormsExtraL10NTestCase(unittest.TestCase): + def setUp(self): + super(FormsExtraL10NTestCase, self).setUp() + self.old_use_l10n = getattr(settings, 'USE_L10N', False) + settings.USE_L10N = True + translation.activate('nl') ->>> from django.utils import translation ->>> translation.activate('nl') ->>> from django.conf import settings ->>> settings.USE_L10N=True + def tearDown(self): + translation.deactivate() + settings.USE_L10N = self.old_use_l10n + super(FormsExtraL10NTestCase, self).tearDown() ->>> w.value_from_datadict({'date_year': '2010', 'date_month': '8', 'date_day': '13'}, {}, 'date') -'13-08-2010' + def test_l10n(self): + w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016'), required=False) + self.assertEqual(w.value_from_datadict({'date_year': '2010', 'date_month': '8', 'date_day': '13'}, {}, 'date'), '13-08-2010') ->>> print w.render('date', '13-08-2010') -<select name="date_day" id="id_date_day"> + self.assertEqual(w.render('date', '13-08-2010'), """<select name="date_day" id="id_date_day"> <option value="0">---</option> <option value="1">1</option> <option value="2">2</option> @@ -433,242 +603,8 @@ USE_L10N tests <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> -</select> +</select>""") -Years before 1900 work ->>> w = SelectDateWidget(years=('1899',)) ->>> w.value_from_datadict({'date_year': '1899', 'date_month': '8', 'date_day': '13'}, {}, 'date') -'13-08-1899' - ->>> translation.deactivate() - -# MultiWidget and MultiValueField ############################################# -# MultiWidgets are widgets composed of other widgets. They are usually -# combined with MultiValueFields - a field that is composed of other fields. -# MulitWidgets can themselved be composed of other MultiWidgets. -# SplitDateTimeWidget is one example of a MultiWidget. - ->>> class ComplexMultiWidget(MultiWidget): -... def __init__(self, attrs=None): -... widgets = ( -... TextInput(), -... SelectMultiple(choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), -... SplitDateTimeWidget(), -... ) -... super(ComplexMultiWidget, self).__init__(widgets, attrs) -... -... def decompress(self, value): -... if value: -... data = value.split(',') -... return [data[0], data[1], datetime.datetime(*time.strptime(data[2], "%Y-%m-%d %H:%M:%S")[0:6])] -... return [None, None, None] -... def format_output(self, rendered_widgets): -... return u'\n'.join(rendered_widgets) ->>> w = ComplexMultiWidget() ->>> print w.render('name', 'some text,JP,2007-04-25 06:24:00') -<input type="text" name="name_0" value="some text" /> -<select multiple="multiple" name="name_1"> -<option value="J" selected="selected">John</option> -<option value="P" selected="selected">Paul</option> -<option value="G">George</option> -<option value="R">Ringo</option> -</select> -<input type="text" name="name_2_0" value="2007-04-25" /><input type="text" name="name_2_1" value="06:24:00" /> - ->>> class ComplexField(MultiValueField): -... def __init__(self, required=True, widget=None, label=None, initial=None): -... fields = ( -... CharField(), -... MultipleChoiceField(choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), -... SplitDateTimeField() -... ) -... super(ComplexField, self).__init__(fields, required, widget, label, initial) -... -... def compress(self, data_list): -... if data_list: -... return '%s,%s,%s' % (data_list[0],''.join(data_list[1]),data_list[2]) -... return None - ->>> f = ComplexField(widget=w) ->>> f.clean(['some text', ['J','P'], ['2007-04-25','6:24:00']]) -u'some text,JP,2007-04-25 06:24:00' ->>> f.clean(['some text',['X'], ['2007-04-25','6:24:00']]) -Traceback (most recent call last): -... -ValidationError: [u'Select a valid choice. X is not one of the available choices.'] - -# If insufficient data is provided, None is substituted ->>> f.clean(['some text',['JP']]) -Traceback (most recent call last): -... -ValidationError: [u'This field is required.'] - ->>> class ComplexFieldForm(Form): -... field1 = ComplexField(widget=w) ->>> f = ComplexFieldForm() ->>> print f -<tr><th><label for="id_field1_0">Field1:</label></th><td><input type="text" name="field1_0" id="id_field1_0" /> -<select multiple="multiple" name="field1_1" id="id_field1_1"> -<option value="J">John</option> -<option value="P">Paul</option> -<option value="G">George</option> -<option value="R">Ringo</option> -</select> -<input type="text" name="field1_2_0" id="id_field1_2_0" /><input type="text" name="field1_2_1" id="id_field1_2_1" /></td></tr> - ->>> f = ComplexFieldForm({'field1_0':'some text','field1_1':['J','P'], 'field1_2_0':'2007-04-25', 'field1_2_1':'06:24:00'}) ->>> print f -<tr><th><label for="id_field1_0">Field1:</label></th><td><input type="text" name="field1_0" value="some text" id="id_field1_0" /> -<select multiple="multiple" name="field1_1" id="id_field1_1"> -<option value="J" selected="selected">John</option> -<option value="P" selected="selected">Paul</option> -<option value="G">George</option> -<option value="R">Ringo</option> -</select> -<input type="text" name="field1_2_0" value="2007-04-25" id="id_field1_2_0" /><input type="text" name="field1_2_1" value="06:24:00" id="id_field1_2_1" /></td></tr> - ->>> f.cleaned_data['field1'] -u'some text,JP,2007-04-25 06:24:00' - - -# IPAddressField ################################################################## - ->>> f = IPAddressField() ->>> f.clean('') -Traceback (most recent call last): -... -ValidationError: [u'This field is required.'] ->>> f.clean(None) -Traceback (most recent call last): -... -ValidationError: [u'This field is required.'] ->>> f.clean('127.0.0.1') -u'127.0.0.1' ->>> f.clean('foo') -Traceback (most recent call last): -... -ValidationError: [u'Enter a valid IPv4 address.'] ->>> f.clean('127.0.0.') -Traceback (most recent call last): -... -ValidationError: [u'Enter a valid IPv4 address.'] ->>> f.clean('1.2.3.4.5') -Traceback (most recent call last): -... -ValidationError: [u'Enter a valid IPv4 address.'] ->>> f.clean('256.125.1.5') -Traceback (most recent call last): -... -ValidationError: [u'Enter a valid IPv4 address.'] - ->>> f = IPAddressField(required=False) ->>> f.clean('') -u'' ->>> f.clean(None) -u'' ->>> f.clean('127.0.0.1') -u'127.0.0.1' ->>> f.clean('foo') -Traceback (most recent call last): -... -ValidationError: [u'Enter a valid IPv4 address.'] ->>> f.clean('127.0.0.') -Traceback (most recent call last): -... -ValidationError: [u'Enter a valid IPv4 address.'] ->>> f.clean('1.2.3.4.5') -Traceback (most recent call last): -... -ValidationError: [u'Enter a valid IPv4 address.'] ->>> f.clean('256.125.1.5') -Traceback (most recent call last): -... -ValidationError: [u'Enter a valid IPv4 address.'] - -################################# -# Tests of underlying functions # -################################# - -# smart_unicode tests ->>> from django.utils.encoding import smart_unicode ->>> class Test: -... def __str__(self): -... return 'ŠĐĆŽćžšđ' ->>> class TestU: -... def __str__(self): -... return 'Foo' -... def __unicode__(self): -... return u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111' ->>> smart_unicode(Test()) -u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111' ->>> smart_unicode(TestU()) -u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111' ->>> smart_unicode(1) -u'1' ->>> smart_unicode('foo') -u'foo' - - -#################################### -# Test accessing errors in clean() # -#################################### - ->>> class UserForm(Form): -... username = CharField(max_length=10) -... password = CharField(widget=PasswordInput) -... def clean(self): -... data = self.cleaned_data -... if not self.errors: -... data['username'] = data['username'].lower() -... return data - ->>> f = UserForm({'username': 'SirRobin', 'password': 'blue'}) ->>> f.is_valid() -True ->>> f.cleaned_data['username'] -u'sirrobin' - -####################################### -# Test overriding ErrorList in a form # -####################################### - ->>> from django.forms.util import ErrorList ->>> class DivErrorList(ErrorList): -... def __unicode__(self): -... return self.as_divs() -... def as_divs(self): -... if not self: return u'' -... return u'<div class="errorlist">%s</div>' % ''.join([u'<div class="error">%s</div>' % force_unicode(e) for e in self]) ->>> class CommentForm(Form): -... name = CharField(max_length=50, required=False) -... email = EmailField() -... comment = CharField() ->>> data = dict(email='invalid') ->>> f = CommentForm(data, auto_id=False, error_class=DivErrorList) ->>> print f.as_p() -<p>Name: <input type="text" name="name" maxlength="50" /></p> -<div class="errorlist"><div class="error">Enter a valid e-mail address.</div></div> -<p>Email: <input type="text" name="email" value="invalid" /></p> -<div class="errorlist"><div class="error">This field is required.</div></div> -<p>Comment: <input type="text" name="comment" /></p> - -################################# -# Test multipart-encoded form # -################################# - ->>> class FormWithoutFile(Form): -... username = CharField() ->>> class FormWithFile(Form): -... username = CharField() -... file = FileField() ->>> class FormWithImage(Form): -... image = ImageField() - ->>> FormWithoutFile().is_multipart() -False ->>> FormWithFile().is_multipart() -True ->>> FormWithImage().is_multipart() -True - -""" + # Years before 1900 work + w = SelectDateWidget(years=('1899',)) + self.assertEqual(w.value_from_datadict({'date_year': '1899', 'date_month': '8', 'date_day': '13'}, {}, 'date'), '13-08-1899') diff --git a/tests/regressiontests/forms/fields.py b/tests/regressiontests/forms/tests/fields.py similarity index 95% rename from tests/regressiontests/forms/fields.py rename to tests/regressiontests/forms/tests/fields.py index b3212eada2..adf4c6e796 100644 --- a/tests/regressiontests/forms/fields.py +++ b/tests/regressiontests/forms/tests/fields.py @@ -57,12 +57,12 @@ class FieldsTests(TestCase): self.assertEqual(message, str(e)) def test_field_sets_widget_is_required(self): - self.assertEqual(Field(required=True).widget.is_required, True) - self.assertEqual(Field(required=False).widget.is_required, False) + self.assertTrue(Field(required=True).widget.is_required) + self.assertFalse(Field(required=False).widget.is_required) # CharField ################################################################### - def test_charfield_0(self): + def test_charfield_1(self): f = CharField() self.assertEqual(u'1', f.clean(1)) self.assertEqual(u'hello', f.clean('hello')) @@ -70,7 +70,7 @@ class FieldsTests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertEqual(u'[1, 2, 3]', f.clean([1, 2, 3])) - def test_charfield_1(self): + def test_charfield_2(self): f = CharField(required=False) self.assertEqual(u'1', f.clean(1)) self.assertEqual(u'hello', f.clean('hello')) @@ -78,20 +78,20 @@ class FieldsTests(TestCase): self.assertEqual(u'', f.clean('')) self.assertEqual(u'[1, 2, 3]', f.clean([1, 2, 3])) - def test_charfield_2(self): + def test_charfield_3(self): f = CharField(max_length=10, required=False) self.assertEqual(u'12345', f.clean('12345')) self.assertEqual(u'1234567890', f.clean('1234567890')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 10 characters (it has 11).']", f.clean, '1234567890a') - def test_charfield_3(self): + def test_charfield_4(self): f = CharField(min_length=10, required=False) self.assertEqual(u'', f.clean('')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 5).']", f.clean, '12345') self.assertEqual(u'1234567890', f.clean('1234567890')) self.assertEqual(u'1234567890a', f.clean('1234567890a')) - def test_charfield_4(self): + def test_charfield_5(self): f = CharField(min_length=10, required=True) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 5).']", f.clean, '12345') @@ -100,7 +100,7 @@ class FieldsTests(TestCase): # IntegerField ################################################################ - def test_integerfield_5(self): + def test_integerfield_1(self): f = IntegerField() self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) @@ -115,7 +115,7 @@ class FieldsTests(TestCase): self.assertEqual(1, f.clean(' 1 ')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, '1a') - def test_integerfield_6(self): + def test_integerfield_2(self): f = IntegerField(required=False) self.assertEqual(None, f.clean('')) self.assertEqual('None', repr(f.clean(''))) @@ -130,7 +130,7 @@ class FieldsTests(TestCase): self.assertEqual(1, f.clean(' 1 ')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, '1a') - def test_integerfield_7(self): + def test_integerfield_3(self): f = IntegerField(max_value=10) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertEqual(1, f.clean(1)) @@ -139,7 +139,7 @@ class FieldsTests(TestCase): self.assertEqual(10, f.clean('10')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 10.']", f.clean, '11') - def test_integerfield_8(self): + def test_integerfield_4(self): f = IntegerField(min_value=10) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 10.']", f.clean, 1) @@ -148,7 +148,7 @@ class FieldsTests(TestCase): self.assertEqual(10, f.clean('10')) self.assertEqual(11, f.clean('11')) - def test_integerfield_9(self): + def test_integerfield_5(self): f = IntegerField(min_value=10, max_value=20) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 10.']", f.clean, 1) @@ -161,7 +161,7 @@ class FieldsTests(TestCase): # FloatField ################################################################## - def test_floatfield_10(self): + def test_floatfield_1(self): f = FloatField() self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) @@ -177,13 +177,13 @@ class FieldsTests(TestCase): self.assertEqual(1.0, f.clean(' 1.0 ')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, '1.0a') - def test_floatfield_11(self): + def test_floatfield_2(self): f = FloatField(required=False) self.assertEqual(None, f.clean('')) self.assertEqual(None, f.clean(None)) self.assertEqual(1.0, f.clean('1')) - def test_floatfield_12(self): + def test_floatfield_3(self): f = FloatField(max_value=1.5, min_value=0.5) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 1.5.']", f.clean, '1.6') self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 0.5.']", f.clean, '0.4') @@ -192,7 +192,7 @@ class FieldsTests(TestCase): # DecimalField ################################################################ - def test_decimalfield_13(self): + def test_decimalfield_1(self): f = DecimalField(max_digits=4, decimal_places=2) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) @@ -223,13 +223,13 @@ class FieldsTests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '-000.12345') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, '--0.12') - def test_decimalfield_14(self): + def test_decimalfield_2(self): f = DecimalField(max_digits=4, decimal_places=2, required=False) self.assertEqual(None, f.clean('')) self.assertEqual(None, f.clean(None)) self.assertEqual(f.clean('1'), Decimal("1")) - def test_decimalfield_15(self): + def test_decimalfield_3(self): f = DecimalField(max_digits=4, decimal_places=2, max_value=Decimal('1.5'), min_value=Decimal('0.5')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 1.5.']", f.clean, '1.6') self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 0.5.']", f.clean, '0.4') @@ -238,11 +238,11 @@ class FieldsTests(TestCase): self.assertEqual(f.clean('.5'), Decimal("0.5")) self.assertEqual(f.clean('00.50'), Decimal("0.50")) - def test_decimalfield_16(self): + def test_decimalfield_4(self): f = DecimalField(decimal_places=2) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '0.00000001') - def test_decimalfield_17(self): + def test_decimalfield_5(self): f = DecimalField(max_digits=3) # Leading whole zeros "collapse" to one digit. self.assertEqual(f.clean('0000000.10'), Decimal("0.1")) @@ -253,14 +253,14 @@ class FieldsTests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 3 digits in total.']", f.clean, '000000.0002') self.assertEqual(f.clean('.002'), Decimal("0.002")) - def test_decimalfield_18(self): + def test_decimalfield_6(self): f = DecimalField(max_digits=2, decimal_places=2) self.assertEqual(f.clean('.01'), Decimal(".01")) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 0 digits before the decimal point.']", f.clean, '1.1') # DateField ################################################################### - def test_datefield_19(self): + def test_datefield_1(self): f = DateField() self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) @@ -279,14 +279,14 @@ class FieldsTests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '25/10/06') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) - def test_datefield_20(self): + def test_datefield_2(self): f = DateField(required=False) self.assertEqual(None, f.clean(None)) self.assertEqual('None', repr(f.clean(None))) self.assertEqual(None, f.clean('')) self.assertEqual('None', repr(f.clean(''))) - def test_datefield_21(self): + def test_datefield_3(self): f = DateField(input_formats=['%Y %m %d']) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) @@ -297,7 +297,7 @@ class FieldsTests(TestCase): # TimeField ################################################################### - def test_timefield_22(self): + def test_timefield_1(self): f = TimeField() self.assertEqual(datetime.time(14, 25), f.clean(datetime.time(14, 25))) self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) @@ -306,7 +306,7 @@ class FieldsTests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, 'hello') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, '1:24 p.m.') - def test_timefield_23(self): + def test_timefield_2(self): f = TimeField(input_formats=['%I:%M %p']) self.assertEqual(datetime.time(14, 25), f.clean(datetime.time(14, 25))) self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) @@ -316,7 +316,7 @@ class FieldsTests(TestCase): # DateTimeField ############################################################### - def test_datetimefield_24(self): + def test_datetimefield_1(self): f = DateTimeField() self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) @@ -337,7 +337,7 @@ class FieldsTests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, 'hello') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, '2006-10-25 4:30 p.m.') - def test_datetimefield_25(self): + def test_datetimefield_2(self): f = DateTimeField(input_formats=['%Y %m %d %I:%M %p']) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) @@ -346,7 +346,7 @@ class FieldsTests(TestCase): self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006 10 25 2:30 PM')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, '2006-10-25 14:30:45') - def test_datetimefield_26(self): + def test_datetimefield_3(self): f = DateTimeField(required=False) self.assertEqual(None, f.clean(None)) self.assertEqual('None', repr(f.clean(None))) @@ -355,7 +355,7 @@ class FieldsTests(TestCase): # RegexField ################################################################## - def test_regexfield_27(self): + def test_regexfield_1(self): f = RegexField('^\d[A-F]\d$') self.assertEqual(u'2A2', f.clean('2A2')) self.assertEqual(u'3F3', f.clean('3F3')) @@ -364,14 +364,14 @@ class FieldsTests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '2A2 ') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') - def test_regexfield_28(self): + def test_regexfield_2(self): f = RegexField('^\d[A-F]\d$', required=False) self.assertEqual(u'2A2', f.clean('2A2')) self.assertEqual(u'3F3', f.clean('3F3')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3') self.assertEqual(u'', f.clean('')) - def test_regexfield_29(self): + def test_regexfield_3(self): f = RegexField(re.compile('^\d[A-F]\d$')) self.assertEqual(u'2A2', f.clean('2A2')) self.assertEqual(u'3F3', f.clean('3F3')) @@ -379,13 +379,13 @@ class FieldsTests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, ' 2A2') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '2A2 ') - def test_regexfield_30(self): + def test_regexfield_4(self): f = RegexField('^\d\d\d\d$', error_message='Enter a four-digit number.') self.assertEqual(u'1234', f.clean('1234')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a four-digit number.']", f.clean, '123') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a four-digit number.']", f.clean, 'abcd') - def test_regexfield_31(self): + def test_regexfield_5(self): f = RegexField('^\d+$', min_length=5, max_length=10) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 5 characters (it has 3).']", f.clean, '123') self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 5 characters (it has 3).', u'Enter a valid value.']", f.clean, 'abc') @@ -396,7 +396,7 @@ class FieldsTests(TestCase): # EmailField ################################################################## - def test_emailfield_32(self): + def test_emailfield_1(self): f = EmailField() self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) @@ -424,7 +424,7 @@ class FieldsTests(TestCase): 'viewx3dtextx26qx3d@yahoo.comx26latlngx3d15854521645943074058' ) - def test_emailfield_33(self): + def test_emailfield_2(self): f = EmailField(required=False) self.assertEqual(u'', f.clean('')) self.assertEqual(u'', f.clean(None)) @@ -434,7 +434,7 @@ class FieldsTests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@bar') - def test_emailfield_34(self): + def test_emailfield_3(self): f = EmailField(min_length=10, max_length=15) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 9).']", f.clean, 'a@foo.com') self.assertEqual(u'alf@foo.com', f.clean('alf@foo.com')) @@ -442,7 +442,7 @@ class FieldsTests(TestCase): # FileField ################################################################## - def test_filefield_35(self): + def test_filefield_1(self): f = FileField() self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '', '') @@ -460,7 +460,7 @@ class FieldsTests(TestCase): self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')))) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content'), 'files/test4.pdf'))) - def test_filefield_36(self): + def test_filefield_2(self): f = FileField(max_length = 5) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this filename has at most 5 characters (it has 18).']", f.clean, SimpleUploadedFile('test_maxlength.txt', 'hello world')) self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) @@ -469,7 +469,7 @@ class FieldsTests(TestCase): # URLField ################################################################## - def test_urlfield_37(self): + def test_urlfield_1(self): f = URLField() self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) @@ -505,7 +505,7 @@ class FieldsTests(TestCase): # domains that don't fail the domain label length check in the regex self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://%s' % ("X"*60,)) - def test_urlfield_38(self): + def test_urlfield_2(self): f = URLField(required=False) self.assertEqual(u'', f.clean('')) self.assertEqual(u'', f.clean(None)) @@ -517,7 +517,7 @@ class FieldsTests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example.') self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://.com') - def test_urlfield_39(self): + def test_urlfield_3(self): f = URLField(verify_exists=True) self.assertEqual(u'http://www.google.com/', f.clean('http://www.google.com')) # This will fail if there's no Internet connection self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example') @@ -539,24 +539,24 @@ class FieldsTests(TestCase): except ValidationError, e: self.assertEqual("[u'This URL appears to be a broken link.']", str(e)) - def test_urlfield_40(self): + def test_urlfield_4(self): f = URLField(verify_exists=True, required=False) self.assertEqual(u'', f.clean('')) self.assertEqual(u'http://www.google.com/', f.clean('http://www.google.com')) # This will fail if there's no Internet connection - def test_urlfield_41(self): + def test_urlfield_5(self): f = URLField(min_length=15, max_length=20) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 15 characters (it has 13).']", f.clean, 'http://f.com') self.assertEqual(u'http://example.com/', f.clean('http://example.com')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 38).']", f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com') - def test_urlfield_42(self): + def test_urlfield_6(self): f = URLField(required=False) self.assertEqual(u'http://example.com/', f.clean('example.com')) self.assertEqual(u'', f.clean('')) self.assertEqual(u'https://example.com/', f.clean('https://example.com')) - def test_urlfield_43(self): + def test_urlfield_7(self): f = URLField() self.assertEqual(u'http://example.com/', f.clean('http://example.com')) self.assertEqual(u'http://example.com/test', f.clean('http://example.com/test')) @@ -567,7 +567,7 @@ class FieldsTests(TestCase): # BooleanField ################################################################ - def test_booleanfield_44(self): + def test_booleanfield_1(self): f = BooleanField() self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) @@ -579,7 +579,7 @@ class FieldsTests(TestCase): self.assertEqual(True, f.clean('True')) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, 'False') - def test_booleanfield_45(self): + def test_booleanfield_2(self): f = BooleanField(required=False) self.assertEqual(False, f.clean('')) self.assertEqual(False, f.clean(None)) @@ -594,7 +594,7 @@ class FieldsTests(TestCase): # ChoiceField ################################################################# - def test_choicefield_46(self): + def test_choicefield_1(self): f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')]) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) @@ -602,7 +602,7 @@ class FieldsTests(TestCase): self.assertEqual(u'1', f.clean('1')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, '3') - def test_choicefield_47(self): + def test_choicefield_2(self): f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) self.assertEqual(u'', f.clean('')) self.assertEqual(u'', f.clean(None)) @@ -610,12 +610,12 @@ class FieldsTests(TestCase): self.assertEqual(u'1', f.clean('1')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, '3') - def test_choicefield_48(self): + def test_choicefield_3(self): f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')]) self.assertEqual(u'J', f.clean('J')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. John is not one of the available choices.']", f.clean, 'John') - def test_choicefield_49(self): + def test_choicefield_4(self): f = ChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')]) self.assertEqual(u'1', f.clean(1)) self.assertEqual(u'1', f.clean('1')) @@ -629,22 +629,22 @@ class FieldsTests(TestCase): # TypedChoiceField is just like ChoiceField, except that coerced types will # be returned: - def test_typedchoicefield_50(self): + def test_typedchoicefield_1(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) self.assertEqual(1, f.clean('1')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 2 is not one of the available choices.']", f.clean, '2') - def test_typedchoicefield_51(self): + def test_typedchoicefield_2(self): # Different coercion, same validation. f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float) self.assertEqual(1.0, f.clean('1')) - def test_typedchoicefield_52(self): + def test_typedchoicefield_3(self): # This can also cause weirdness: be careful (bool(-1) == True, remember) f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool) self.assertEqual(True, f.clean('-1')) - def test_typedchoicefield_53(self): + def test_typedchoicefield_4(self): # Even more weirdness: if you have a valid choice but your coercion function # can't coerce, you'll still get a validation error. Don't do this! f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) @@ -652,19 +652,19 @@ class FieldsTests(TestCase): # Required fields require values self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') - def test_typedchoicefield_54(self): + def test_typedchoicefield_5(self): # Non-required fields aren't required f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False) self.assertEqual('', f.clean('')) # If you want cleaning an empty value to return a different type, tell the field - def test_typedchoicefield_55(self): + def test_typedchoicefield_6(self): f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None) self.assertEqual(None, f.clean('')) # NullBooleanField ############################################################ - def test_nullbooleanfield_56(self): + def test_nullbooleanfield_1(self): f = NullBooleanField() self.assertEqual(None, f.clean('')) self.assertEqual(True, f.clean(True)) @@ -677,7 +677,7 @@ class FieldsTests(TestCase): self.assertEqual(None, f.clean('hello')) - def test_nullbooleanfield_57(self): + def test_nullbooleanfield_2(self): # Make sure that the internal value is preserved if using HiddenInput (#7753) class HiddenNullBooleanForm(Form): hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True) @@ -685,7 +685,7 @@ class FieldsTests(TestCase): f = HiddenNullBooleanForm() self.assertEqual('<input type="hidden" name="hidden_nullbool1" value="True" id="id_hidden_nullbool1" /><input type="hidden" name="hidden_nullbool2" value="False" id="id_hidden_nullbool2" />', str(f)) - def test_nullbooleanfield_58(self): + def test_nullbooleanfield_3(self): class HiddenNullBooleanForm(Form): hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True) hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False) @@ -694,7 +694,7 @@ class FieldsTests(TestCase): self.assertEqual(True, f.cleaned_data['hidden_nullbool1']) self.assertEqual(False, f.cleaned_data['hidden_nullbool2']) - def test_nullbooleanfield_59(self): + def test_nullbooleanfield_4(self): # Make sure we're compatible with MySQL, which uses 0 and 1 for its boolean # values. (#9609) NULLBOOL_CHOICES = (('1', 'Yes'), ('0', 'No'), ('', 'Unknown')) @@ -710,7 +710,7 @@ class FieldsTests(TestCase): # MultipleChoiceField ######################################################### - def test_multiplechoicefield_60(self): + def test_multiplechoicefield_1(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')]) self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) @@ -724,7 +724,7 @@ class FieldsTests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, ()) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, ['3']) - def test_multiplechoicefield_61(self): + def test_multiplechoicefield_2(self): f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) self.assertEqual([], f.clean('')) self.assertEqual([], f.clean(None)) @@ -738,7 +738,7 @@ class FieldsTests(TestCase): self.assertEqual([], f.clean(())) self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, ['3']) - def test_multiplechoicefield_62(self): + def test_multiplechoicefield_3(self): f = MultipleChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')]) self.assertEqual([u'1'], f.clean([1])) self.assertEqual([u'1'], f.clean(['1'])) @@ -751,7 +751,7 @@ class FieldsTests(TestCase): # ComboField ################################################################## - def test_combofield_63(self): + def test_combofield_1(self): f = ComboField(fields=[CharField(max_length=20), EmailField()]) self.assertEqual(u'test@example.com', f.clean('test@example.com')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 28).']", f.clean, 'longemailaddress@example.com') @@ -759,7 +759,7 @@ class FieldsTests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) - def test_combofield_64(self): + def test_combofield_2(self): f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False) self.assertEqual(u'test@example.com', f.clean('test@example.com')) self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 28).']", f.clean, 'longemailaddress@example.com') @@ -769,12 +769,12 @@ class FieldsTests(TestCase): # FilePathField ############################################################### - def test_filepathfield_65(self): + def test_filepathfield_1(self): path = os.path.abspath(forms.__file__) path = os.path.dirname(path) + '/' self.assertTrue(fix_os_paths(path).endswith('/django/forms/')) - def test_filepathfield_66(self): + def test_filepathfield_2(self): path = forms.__file__ path = os.path.dirname(os.path.abspath(path)) + '/' f = FilePathField(path=path) @@ -795,7 +795,7 @@ class FieldsTests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. fields.py is not one of the available choices.']", f.clean, 'fields.py') assert fix_os_paths(f.clean(path + 'fields.py')).endswith('/django/forms/fields.py') - def test_filepathfield_67(self): + def test_filepathfield_3(self): path = forms.__file__ path = os.path.dirname(os.path.abspath(path)) + '/' f = FilePathField(path=path, match='^.*?\.py$') @@ -813,7 +813,7 @@ class FieldsTests(TestCase): self.assertEqual(exp[1], got[1]) self.assertTrue(got[0].endswith(exp[0])) - def test_filepathfield_68(self): + def test_filepathfield_4(self): path = os.path.abspath(forms.__file__) path = os.path.dirname(path) + '/' f = FilePathField(path=path, recursive=True, match='^.*?\.py$') @@ -835,7 +835,7 @@ class FieldsTests(TestCase): # SplitDateTimeField ########################################################## - def test_splitdatetimefield_69(self): + def test_splitdatetimefield_1(self): from django.forms.widgets import SplitDateTimeWidget f = SplitDateTimeField() assert isinstance(f.widget, SplitDateTimeWidget) @@ -847,7 +847,7 @@ class FieldsTests(TestCase): self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', 'there']) self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['hello', '07:30']) - def test_splitdatetimefield_70(self): + def test_splitdatetimefield_2(self): f = SplitDateTimeField(required=False) self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])) self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean(['2006-01-10', '07:30'])) diff --git a/tests/regressiontests/forms/tests/forms.py b/tests/regressiontests/forms/tests/forms.py new file mode 100644 index 0000000000..b52a0537ee --- /dev/null +++ b/tests/regressiontests/forms/tests/forms.py @@ -0,0 +1,1709 @@ +# -*- coding: utf-8 -*- +import datetime +from decimal import Decimal +import re +import time +from django.core.files.uploadedfile import SimpleUploadedFile +from django.forms import * +from django.http import QueryDict +from django.template import Template, Context +from django.utils.datastructures import MultiValueDict, MergeDict +from django.utils.safestring import mark_safe +from django.utils.unittest import TestCase + + +class Person(Form): + first_name = CharField() + last_name = CharField() + birthday = DateField() + + +class PersonNew(Form): + first_name = CharField(widget=TextInput(attrs={'id': 'first_name_id'})) + last_name = CharField() + birthday = DateField() + + +class FormsTestCase(TestCase): + # A Form is a collection of Fields. It knows how to validate a set of data and it + # knows how to render itself in a couple of default ways (e.g., an HTML table). + # You can pass it data in __init__(), as a dictionary. + + def test_form(self): + # Pass a dictionary to a Form's __init__(). + p = Person({'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9'}) + + self.assertTrue(p.is_bound) + self.assertEqual(p.errors, {}) + self.assertTrue(p.is_valid()) + self.assertEqual(p.errors.as_ul(), u'') + self.assertEqual(p.errors.as_text(), u'') + self.assertEqual(p.cleaned_data["first_name"], u'John') + self.assertEqual(p.cleaned_data["last_name"], u'Lennon') + self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) + self.assertEqual(str(p['first_name']), '<input type="text" name="first_name" value="John" id="id_first_name" />') + self.assertEqual(str(p['last_name']), '<input type="text" name="last_name" value="Lennon" id="id_last_name" />') + self.assertEqual(str(p['birthday']), '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" />') + try: + p['nonexistentfield'] + self.fail('Attempts to access non-existent fields should fail.') + except KeyError: + pass + + form_output = [] + + for boundfield in p: + form_output.append(str(boundfield)) + + self.assertEqual('\n'.join(form_output), """<input type="text" name="first_name" value="John" id="id_first_name" /> +<input type="text" name="last_name" value="Lennon" id="id_last_name" /> +<input type="text" name="birthday" value="1940-10-9" id="id_birthday" />""") + + form_output = [] + + for boundfield in p: + form_output.append([boundfield.label, boundfield.data]) + + self.assertEqual(form_output, [ + ['First name', u'John'], + ['Last name', u'Lennon'], + ['Birthday', u'1940-10-9'] + ]) + self.assertEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr> +<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="Lennon" id="id_last_name" /></td></tr> +<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>""") + + def test_empty_dict(self): + # Empty dictionaries are valid, too. + p = Person({}) + self.assertTrue(p.is_bound) + self.assertEqual(p.errors['first_name'], [u'This field is required.']) + self.assertEqual(p.errors['last_name'], [u'This field is required.']) + self.assertEqual(p.errors['birthday'], [u'This field is required.']) + self.assertFalse(p.is_valid()) + try: + p.cleaned_data + self.fail('Attempts to access cleaned_data when validation fails should fail.') + except AttributeError: + pass + self.assertEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" id="id_first_name" /></td></tr> +<tr><th><label for="id_last_name">Last name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="last_name" id="id_last_name" /></td></tr> +<tr><th><label for="id_birthday">Birthday:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="birthday" id="id_birthday" /></td></tr>""") + self.assertEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" id="id_first_name" /></td></tr> +<tr><th><label for="id_last_name">Last name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="last_name" id="id_last_name" /></td></tr> +<tr><th><label for="id_birthday">Birthday:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="birthday" id="id_birthday" /></td></tr>""") + self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li> +<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li> +<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li>""") + self.assertEqual(p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul> +<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p> +<ul class="errorlist"><li>This field is required.</li></ul> +<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p> +<ul class="errorlist"><li>This field is required.</li></ul> +<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>""") + + def test_unbound_form(self): + # If you don't pass any values to the Form's __init__(), or if you pass None, + # the Form will be considered unbound and won't do any validation. Form.errors + # will be an empty dictionary *but* Form.is_valid() will return False. + p = Person() + self.assertFalse(p.is_bound) + self.assertEqual(p.errors, {}) + self.assertFalse(p.is_valid()) + try: + p.cleaned_data + self.fail('Attempts to access cleaned_data when validation fails should fail.') + except AttributeError: + pass + self.assertEqual(str(p), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr> +<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr> +<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>""") + self.assertEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr> +<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr> +<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>""") + self.assertEqual(p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li> +<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li> +<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li>""") + self.assertEqual(p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p> +<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p> +<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>""") + + def test_unicode_values(self): + # Unicode values are handled properly. + p = Person({'first_name': u'John', 'last_name': u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'}) + self.assertEqual(p.as_table(), u'<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>\n<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></td></tr>\n<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>') + self.assertEqual(p.as_ul(), u'<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></li>\n<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></li>\n<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></li>') + self.assertEqual(p.as_p(), u'<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></p>\n<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></p>\n<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></p>') + + p = Person({'last_name': u'Lennon'}) + self.assertEqual(p.errors['first_name'], [u'This field is required.']) + self.assertEqual(p.errors['birthday'], [u'This field is required.']) + self.assertFalse(p.is_valid()) + self.assertEqual(p.errors.as_ul(), u'<ul class="errorlist"><li>first_name<ul class="errorlist"><li>This field is required.</li></ul></li><li>birthday<ul class="errorlist"><li>This field is required.</li></ul></li></ul>') + self.assertEqual(p.errors.as_text(), """* first_name + * This field is required. +* birthday + * This field is required.""") + try: + p.cleaned_data + self.fail('Attempts to access cleaned_data when validation fails should fail.') + except AttributeError: + pass + self.assertEqual(p['first_name'].errors, [u'This field is required.']) + self.assertEqual(p['first_name'].errors.as_ul(), u'<ul class="errorlist"><li>This field is required.</li></ul>') + self.assertEqual(p['first_name'].errors.as_text(), u'* This field is required.') + + p = Person() + self.assertEqual(str(p['first_name']), '<input type="text" name="first_name" id="id_first_name" />') + self.assertEqual(str(p['last_name']), '<input type="text" name="last_name" id="id_last_name" />') + self.assertEqual(str(p['birthday']), '<input type="text" name="birthday" id="id_birthday" />') + + def test_cleaned_data_only_fields(self): + # cleaned_data will always *only* contain a key for fields defined in the + # Form, even if you pass extra data when you define the Form. In this + # example, we pass a bunch of extra fields to the form constructor, + # but cleaned_data contains only the form's fields. + data = {'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9', 'extra1': 'hello', 'extra2': 'hello'} + p = Person(data) + self.assertTrue(p.is_valid()) + self.assertEqual(p.cleaned_data['first_name'], u'John') + self.assertEqual(p.cleaned_data['last_name'], u'Lennon') + self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9)) + + def test_optional_data(self): + # cleaned_data will include a key and value for *all* fields defined in the Form, + # even if the Form's data didn't include a value for fields that are not + # required. In this example, the data dictionary doesn't include a value for the + # "nick_name" field, but cleaned_data includes it. For CharFields, it's set to the + # empty string. + class OptionalPersonForm(Form): + first_name = CharField() + last_name = CharField() + nick_name = CharField(required=False) + + data = {'first_name': u'John', 'last_name': u'Lennon'} + f = OptionalPersonForm(data) + self.assertTrue(f.is_valid()) + self.assertEqual(f.cleaned_data['nick_name'], u'') + self.assertEqual(f.cleaned_data['first_name'], u'John') + self.assertEqual(f.cleaned_data['last_name'], u'Lennon') + + # For DateFields, it's set to None. + class OptionalPersonForm(Form): + first_name = CharField() + last_name = CharField() + birth_date = DateField(required=False) + + data = {'first_name': u'John', 'last_name': u'Lennon'} + f = OptionalPersonForm(data) + self.assertTrue(f.is_valid()) + self.assertEqual(f.cleaned_data['birth_date'], None) + self.assertEqual(f.cleaned_data['first_name'], u'John') + self.assertEqual(f.cleaned_data['last_name'], u'Lennon') + + def test_auto_id(self): + # "auto_id" tells the Form to add an "id" attribute to each form element. + # If it's a string that contains '%s', Django will use that as a format string + # into which the field's name will be inserted. It will also put a <label> around + # the human-readable labels for a field. + p = Person(auto_id='%s_id') + self.assertEqual(p.as_table(), """<tr><th><label for="first_name_id">First name:</label></th><td><input type="text" name="first_name" id="first_name_id" /></td></tr> +<tr><th><label for="last_name_id">Last name:</label></th><td><input type="text" name="last_name" id="last_name_id" /></td></tr> +<tr><th><label for="birthday_id">Birthday:</label></th><td><input type="text" name="birthday" id="birthday_id" /></td></tr>""") + self.assertEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" /></li> +<li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></li> +<li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></li>""") + self.assertEqual(p.as_p(), """<p><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" /></p> +<p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></p> +<p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></p>""") + + def test_auto_id_true(self): + # If auto_id is any True value whose str() does not contain '%s', the "id" + # attribute will be the name of the field. + p = Person(auto_id=True) + self.assertEqual(p.as_ul(), """<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" /></li> +<li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li> +<li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>""") + + def test_auto_id_false(self): + # If auto_id is any False value, an "id" attribute won't be output unless it + # was manually entered. + p = Person(auto_id=False) + self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li> +<li>Last name: <input type="text" name="last_name" /></li> +<li>Birthday: <input type="text" name="birthday" /></li>""") + + def test_id_on_field(self): + # In this example, auto_id is False, but the "id" attribute for the "first_name" + # field is given. Also note that field gets a <label>, while the others don't. + p = PersonNew(auto_id=False) + self.assertEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" /></li> +<li>Last name: <input type="text" name="last_name" /></li> +<li>Birthday: <input type="text" name="birthday" /></li>""") + + def test_auto_id_on_form_and_field(self): + # If the "id" attribute is specified in the Form and auto_id is True, the "id" + # attribute in the Form gets precedence. + p = PersonNew(auto_id=True) + self.assertEqual(p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" /></li> +<li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li> +<li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>""") + + def test_various_boolean_values(self): + class SignupForm(Form): + email = EmailField() + get_spam = BooleanField() + + f = SignupForm(auto_id=False) + self.assertEqual(str(f['email']), '<input type="text" name="email" />') + self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />') + + f = SignupForm({'email': 'test@example.com', 'get_spam': True}, auto_id=False) + self.assertEqual(str(f['email']), '<input type="text" name="email" value="test@example.com" />') + self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />') + + # 'True' or 'true' should be rendered without a value attribute + f = SignupForm({'email': 'test@example.com', 'get_spam': 'True'}, auto_id=False) + self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />') + + f = SignupForm({'email': 'test@example.com', 'get_spam': 'true'}, auto_id=False) + self.assertEqual(str(f['get_spam']), '<input checked="checked" type="checkbox" name="get_spam" />') + + # A value of 'False' or 'false' should be rendered unchecked + f = SignupForm({'email': 'test@example.com', 'get_spam': 'False'}, auto_id=False) + self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />') + + f = SignupForm({'email': 'test@example.com', 'get_spam': 'false'}, auto_id=False) + self.assertEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />') + + def test_widget_output(self): + # Any Field can have a Widget class passed to its constructor: + class ContactForm(Form): + subject = CharField() + message = CharField(widget=Textarea) + + f = ContactForm(auto_id=False) + self.assertEqual(str(f['subject']), '<input type="text" name="subject" />') + self.assertEqual(str(f['message']), '<textarea rows="10" cols="40" name="message"></textarea>') + + # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output + # widget type: + self.assertEqual(f['subject'].as_textarea(), u'<textarea rows="10" cols="40" name="subject"></textarea>') + self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" />') + self.assertEqual(f['message'].as_hidden(), u'<input type="hidden" name="message" />') + + # The 'widget' parameter to a Field can also be an instance: + class ContactForm(Form): + subject = CharField() + message = CharField(widget=Textarea(attrs={'rows': 80, 'cols': 20})) + + f = ContactForm(auto_id=False) + self.assertEqual(str(f['message']), '<textarea rows="80" cols="20" name="message"></textarea>') + + # Instance-level attrs are *not* carried over to as_textarea(), as_text() and + # as_hidden(): + self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" />') + f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False) + self.assertEqual(f['subject'].as_textarea(), u'<textarea rows="10" cols="40" name="subject">Hello</textarea>') + self.assertEqual(f['message'].as_text(), u'<input type="text" name="message" value="I love you." />') + self.assertEqual(f['message'].as_hidden(), u'<input type="hidden" name="message" value="I love you." />') + + def test_forms_with_choices(self): + # For a form with a <select>, use ChoiceField: + class FrameworkForm(Form): + name = CharField() + language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')]) + + f = FrameworkForm(auto_id=False) + self.assertEqual(str(f['language']), """<select name="language"> +<option value="P">Python</option> +<option value="J">Java</option> +</select>""") + f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) + self.assertEqual(str(f['language']), """<select name="language"> +<option value="P" selected="selected">Python</option> +<option value="J">Java</option> +</select>""") + + # A subtlety: If one of the choices' value is the empty string and the form is + # unbound, then the <option> for the empty-string choice will get selected="selected". + class FrameworkForm(Form): + name = CharField() + language = ChoiceField(choices=[('', '------'), ('P', 'Python'), ('J', 'Java')]) + + f = FrameworkForm(auto_id=False) + self.assertEqual(str(f['language']), """<select name="language"> +<option value="" selected="selected">------</option> +<option value="P">Python</option> +<option value="J">Java</option> +</select>""") + + # You can specify widget attributes in the Widget constructor. + class FrameworkForm(Form): + name = CharField() + language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(attrs={'class': 'foo'})) + + f = FrameworkForm(auto_id=False) + self.assertEqual(str(f['language']), """<select class="foo" name="language"> +<option value="P">Python</option> +<option value="J">Java</option> +</select>""") + f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) + self.assertEqual(str(f['language']), """<select class="foo" name="language"> +<option value="P" selected="selected">Python</option> +<option value="J">Java</option> +</select>""") + + # When passing a custom widget instance to ChoiceField, note that setting + # 'choices' on the widget is meaningless. The widget will use the choices + # defined on the Field, not the ones defined on the Widget. + class FrameworkForm(Form): + name = CharField() + language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'})) + + f = FrameworkForm(auto_id=False) + self.assertEqual(str(f['language']), """<select class="foo" name="language"> +<option value="P">Python</option> +<option value="J">Java</option> +</select>""") + f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False) + self.assertEqual(str(f['language']), """<select class="foo" name="language"> +<option value="P" selected="selected">Python</option> +<option value="J">Java</option> +</select>""") + + # You can set a ChoiceField's choices after the fact. + class FrameworkForm(Form): + name = CharField() + language = ChoiceField() + + f = FrameworkForm(auto_id=False) + self.assertEqual(str(f['language']), """<select name="language"> +</select>""") + f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')] + self.assertEqual(str(f['language']), """<select name="language"> +<option value="P">Python</option> +<option value="J">Java</option> +</select>""") + + def test_forms_with_radio(self): + # Add widget=RadioSelect to use that widget with a ChoiceField. + class FrameworkForm(Form): + name = CharField() + language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=RadioSelect) + + f = FrameworkForm(auto_id=False) + self.assertEqual(str(f['language']), """<ul> +<li><label><input type="radio" name="language" value="P" /> Python</label></li> +<li><label><input type="radio" name="language" value="J" /> Java</label></li> +</ul>""") + self.assertEqual(f.as_table(), """<tr><th>Name:</th><td><input type="text" name="name" /></td></tr> +<tr><th>Language:</th><td><ul> +<li><label><input type="radio" name="language" value="P" /> Python</label></li> +<li><label><input type="radio" name="language" value="J" /> Java</label></li> +</ul></td></tr>""") + self.assertEqual(f.as_ul(), """<li>Name: <input type="text" name="name" /></li> +<li>Language: <ul> +<li><label><input type="radio" name="language" value="P" /> Python</label></li> +<li><label><input type="radio" name="language" value="J" /> Java</label></li> +</ul></li>""") + + # Regarding auto_id and <label>, RadioSelect is a special case. Each radio button + # gets a distinct ID, formed by appending an underscore plus the button's + # zero-based index. + f = FrameworkForm(auto_id='id_%s') + self.assertEqual(str(f['language']), """<ul> +<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li> +<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li> +</ul>""") + + # When RadioSelect is used with auto_id, and the whole form is printed using + # either as_table() or as_ul(), the label for the RadioSelect will point to the + # ID of the *first* radio button. + self.assertEqual(f.as_table(), """<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" id="id_name" /></td></tr> +<tr><th><label for="id_language_0">Language:</label></th><td><ul> +<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li> +<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li> +</ul></td></tr>""") + self.assertEqual(f.as_ul(), """<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></li> +<li><label for="id_language_0">Language:</label> <ul> +<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li> +<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li> +</ul></li>""") + self.assertEqual(f.as_p(), """<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p> +<p><label for="id_language_0">Language:</label> <ul> +<li><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li> +<li><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li> +</ul></p>""") + + def test_forms_wit_hmultiple_choice(self): + # MultipleChoiceField is a special case, as its data is required to be a list: + class SongForm(Form): + name = CharField() + composers = MultipleChoiceField() + + f = SongForm(auto_id=False) + self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers"> +</select>""") + + class SongForm(Form): + name = CharField() + composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')]) + + f = SongForm(auto_id=False) + self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers"> +<option value="J">John Lennon</option> +<option value="P">Paul McCartney</option> +</select>""") + f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False) + self.assertEqual(str(f['name']), '<input type="text" name="name" value="Yesterday" />') + self.assertEqual(str(f['composers']), """<select multiple="multiple" name="composers"> +<option value="J">John Lennon</option> +<option value="P" selected="selected">Paul McCartney</option> +</select>""") + + def test_hidden_data(self): + class SongForm(Form): + name = CharField() + composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')]) + + # MultipleChoiceField rendered as_hidden() is a special case. Because it can + # have multiple values, its as_hidden() renders multiple <input type="hidden"> + # tags. + f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False) + self.assertEqual(f['composers'].as_hidden(), '<input type="hidden" name="composers" value="P" />') + f = SongForm({'name': 'From Me To You', 'composers': ['P', 'J']}, auto_id=False) + self.assertEqual(f['composers'].as_hidden(), """<input type="hidden" name="composers" value="P" /> +<input type="hidden" name="composers" value="J" />""") + + # DateTimeField rendered as_hidden() is special too + class MessageForm(Form): + when = SplitDateTimeField() + + f = MessageForm({'when_0': '1992-01-01', 'when_1': '01:01'}) + self.assertTrue(f.is_valid()) + self.assertEqual(str(f['when']), '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" /><input type="text" name="when_1" value="01:01" id="id_when_1" />') + self.assertEqual(f['when'].as_hidden(), '<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0" /><input type="hidden" name="when_1" value="01:01" id="id_when_1" />') + + def test_mulitple_choice_checkbox(self): + # MultipleChoiceField can also be used with the CheckboxSelectMultiple widget. + class SongForm(Form): + name = CharField() + composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple) + + f = SongForm(auto_id=False) + self.assertEqual(str(f['composers']), """<ul> +<li><label><input type="checkbox" name="composers" value="J" /> John Lennon</label></li> +<li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li> +</ul>""") + f = SongForm({'composers': ['J']}, auto_id=False) + self.assertEqual(str(f['composers']), """<ul> +<li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li> +<li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li> +</ul>""") + f = SongForm({'composers': ['J', 'P']}, auto_id=False) + self.assertEqual(str(f['composers']), """<ul> +<li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li> +<li><label><input checked="checked" type="checkbox" name="composers" value="P" /> Paul McCartney</label></li> +</ul>""") + + def test_checkbox_auto_id(self): + # Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox + # gets a distinct ID, formed by appending an underscore plus the checkbox's + # zero-based index. + class SongForm(Form): + name = CharField() + composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple) + + f = SongForm(auto_id='%s_id') + self.assertEqual(str(f['composers']), """<ul> +<li><label for="composers_id_0"><input type="checkbox" name="composers" value="J" id="composers_id_0" /> John Lennon</label></li> +<li><label for="composers_id_1"><input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li> +</ul>""") + + def test_multiple_choice_list_data(self): + # Data for a MultipleChoiceField should be a list. QueryDict, MultiValueDict and + # MergeDict (when created as a merge of MultiValueDicts) conveniently work with + # this. + class SongForm(Form): + name = CharField() + composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple) + + data = {'name': 'Yesterday', 'composers': ['J', 'P']} + f = SongForm(data) + self.assertEqual(f.errors, {}) + + data = QueryDict('name=Yesterday&composers=J&composers=P') + f = SongForm(data) + self.assertEqual(f.errors, {}) + + data = MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])) + f = SongForm(data) + self.assertEqual(f.errors, {}) + + data = MergeDict(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P']))) + f = SongForm(data) + self.assertEqual(f.errors, {}) + + def test_multiple_hidden(self): + class SongForm(Form): + name = CharField() + composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple) + + # The MultipleHiddenInput widget renders multiple values as hidden fields. + class SongFormHidden(Form): + name = CharField() + composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=MultipleHiddenInput) + + f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False) + self.assertEqual(f.as_ul(), """<li>Name: <input type="text" name="name" value="Yesterday" /><input type="hidden" name="composers" value="J" /> +<input type="hidden" name="composers" value="P" /></li>""") + + # When using CheckboxSelectMultiple, the framework expects a list of input and + # returns a list of input. + f = SongForm({'name': 'Yesterday'}, auto_id=False) + self.assertEqual(f.errors['composers'], [u'This field is required.']) + f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False) + self.assertEqual(f.errors, {}) + self.assertEqual(f.cleaned_data['composers'], [u'J']) + self.assertEqual(f.cleaned_data['name'], u'Yesterday') + f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False) + self.assertEqual(f.errors, {}) + self.assertEqual(f.cleaned_data['composers'], [u'J', u'P']) + self.assertEqual(f.cleaned_data['name'], u'Yesterday') + + def test_escaping(self): + # Validation errors are HTML-escaped when output as HTML. + class EscapingForm(Form): + special_name = CharField(label="<em>Special</em> Field") + special_safe_name = CharField(label=mark_safe("<em>Special</em> Field")) + + def clean_special_name(self): + raise ValidationError("Something's wrong with '%s'" % self.cleaned_data['special_name']) + + def clean_special_safe_name(self): + raise ValidationError(mark_safe("'<b>%s</b>' is a safe string" % self.cleaned_data['special_safe_name'])) + + f = EscapingForm({'special_name': "Nothing to escape", 'special_safe_name': "Nothing to escape"}, auto_id=False) + self.assertEqual(f.as_table(), """<tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>Something's wrong with 'Nothing to escape'</li></ul><input type="text" name="special_name" value="Nothing to escape" /></td></tr> +<tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>'<b>Nothing to escape</b>' is a safe string</li></ul><input type="text" name="special_safe_name" value="Nothing to escape" /></td></tr>""") + f = EscapingForm({ + 'special_name': "Should escape < & > and <script>alert('xss')</script>", + 'special_safe_name': "<i>Do not escape</i>" + }, auto_id=False) + self.assertEqual(f.as_table(), """<tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>Something's wrong with 'Should escape < & > and <script>alert('xss')</script>'</li></ul><input type="text" name="special_name" value="Should escape < & > and <script>alert('xss')</script>" /></td></tr> +<tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>'<b><i>Do not escape</i></b>' is a safe string</li></ul><input type="text" name="special_safe_name" value="<i>Do not escape</i>" /></td></tr>""") + + def test_validating_multiple_fields(self): + # There are a couple of ways to do multiple-field validation. If you want the + # validation message to be associated with a particular field, implement the + # clean_XXX() method on the Form, where XXX is the field name. As in + # Field.clean(), the clean_XXX() method should return the cleaned value. In the + # clean_XXX() method, you have access to self.cleaned_data, which is a dictionary + # of all the data that has been cleaned *so far*, in order by the fields, + # including the current field (e.g., the field XXX if you're in clean_XXX()). + class UserRegistration(Form): + username = CharField(max_length=10) + password1 = CharField(widget=PasswordInput) + password2 = CharField(widget=PasswordInput) + + def clean_password2(self): + if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: + raise ValidationError(u'Please make sure your passwords match.') + + return self.cleaned_data['password2'] + + f = UserRegistration(auto_id=False) + self.assertEqual(f.errors, {}) + f = UserRegistration({}, auto_id=False) + self.assertEqual(f.errors['username'], [u'This field is required.']) + self.assertEqual(f.errors['password1'], [u'This field is required.']) + self.assertEqual(f.errors['password2'], [u'This field is required.']) + f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) + self.assertEqual(f.errors['password2'], [u'Please make sure your passwords match.']) + f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False) + self.assertEqual(f.errors, {}) + self.assertEqual(f.cleaned_data['username'], u'adrian') + self.assertEqual(f.cleaned_data['password1'], u'foo') + self.assertEqual(f.cleaned_data['password2'], u'foo') + + # Another way of doing multiple-field validation is by implementing the + # Form's clean() method. If you do this, any ValidationError raised by that + # method will not be associated with a particular field; it will have a + # special-case association with the field named '__all__'. + # Note that in Form.clean(), you have access to self.cleaned_data, a dictionary of + # all the fields/values that have *not* raised a ValidationError. Also note + # Form.clean() is required to return a dictionary of all clean data. + class UserRegistration(Form): + username = CharField(max_length=10) + password1 = CharField(widget=PasswordInput) + password2 = CharField(widget=PasswordInput) + + def clean(self): + if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: + raise ValidationError(u'Please make sure your passwords match.') + + return self.cleaned_data + + f = UserRegistration(auto_id=False) + self.assertEqual(f.errors, {}) + f = UserRegistration({}, auto_id=False) + self.assertEqual(f.as_table(), """<tr><th>Username:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="username" maxlength="10" /></td></tr> +<tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password1" /></td></tr> +<tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password2" /></td></tr>""") + self.assertEqual(f.errors['username'], [u'This field is required.']) + self.assertEqual(f.errors['password1'], [u'This field is required.']) + self.assertEqual(f.errors['password2'], [u'This field is required.']) + f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False) + self.assertEqual(f.errors['__all__'], [u'Please make sure your passwords match.']) + self.assertEqual(f.as_table(), """<tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr> +<tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" /></td></tr> +<tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr> +<tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>""") + self.assertEqual(f.as_ul(), """<li><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></li> +<li>Username: <input type="text" name="username" value="adrian" maxlength="10" /></li> +<li>Password1: <input type="password" name="password1" /></li> +<li>Password2: <input type="password" name="password2" /></li>""") + f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False) + self.assertEqual(f.errors, {}) + self.assertEqual(f.cleaned_data['username'], u'adrian') + self.assertEqual(f.cleaned_data['password1'], u'foo') + self.assertEqual(f.cleaned_data['password2'], u'foo') + + def test_dynamic_construction(self): + # It's possible to construct a Form dynamically by adding to the self.fields + # dictionary in __init__(). Don't forget to call Form.__init__() within the + # subclass' __init__(). + class Person(Form): + first_name = CharField() + last_name = CharField() + + def __init__(self, *args, **kwargs): + super(Person, self).__init__(*args, **kwargs) + self.fields['birthday'] = DateField() + + p = Person(auto_id=False) + self.assertEqual(p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr> +<tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr> +<tr><th>Birthday:</th><td><input type="text" name="birthday" /></td></tr>""") + + # Instances of a dynamic Form do not persist fields from one Form instance to + # the next. + class MyForm(Form): + def __init__(self, data=None, auto_id=False, field_list=[]): + Form.__init__(self, data, auto_id=auto_id) + + for field in field_list: + self.fields[field[0]] = field[1] + + field_list = [('field1', CharField()), ('field2', CharField())] + my_form = MyForm(field_list=field_list) + self.assertEqual(my_form.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr> +<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>""") + field_list = [('field3', CharField()), ('field4', CharField())] + my_form = MyForm(field_list=field_list) + self.assertEqual(my_form.as_table(), """<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr> +<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>""") + + class MyForm(Form): + default_field_1 = CharField() + default_field_2 = CharField() + + def __init__(self, data=None, auto_id=False, field_list=[]): + Form.__init__(self, data, auto_id=auto_id) + + for field in field_list: + self.fields[field[0]] = field[1] + + field_list = [('field1', CharField()), ('field2', CharField())] + my_form = MyForm(field_list=field_list) + self.assertEqual(my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr> +<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr> +<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr> +<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>""") + field_list = [('field3', CharField()), ('field4', CharField())] + my_form = MyForm(field_list=field_list) + self.assertEqual(my_form.as_table(), """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr> +<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr> +<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr> +<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>""") + + # Similarly, changes to field attributes do not persist from one Form instance + # to the next. + class Person(Form): + first_name = CharField(required=False) + last_name = CharField(required=False) + + def __init__(self, names_required=False, *args, **kwargs): + super(Person, self).__init__(*args, **kwargs) + + if names_required: + self.fields['first_name'].required = True + self.fields['first_name'].widget.attrs['class'] = 'required' + self.fields['last_name'].required = True + self.fields['last_name'].widget.attrs['class'] = 'required' + + f = Person(names_required=False) + self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False)) + self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {})) + f = Person(names_required=True) + self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (True, True)) + self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({'class': 'required'}, {'class': 'required'})) + f = Person(names_required=False) + self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False)) + self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {})) + + class Person(Form): + first_name = CharField(max_length=30) + last_name = CharField(max_length=30) + + def __init__(self, name_max_length=None, *args, **kwargs): + super(Person, self).__init__(*args, **kwargs) + + if name_max_length: + self.fields['first_name'].max_length = name_max_length + self.fields['last_name'].max_length = name_max_length + + f = Person(name_max_length=None) + self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30)) + f = Person(name_max_length=20) + self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (20, 20)) + f = Person(name_max_length=None) + self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30)) + + def test_hidden_widget(self): + # HiddenInput widgets are displayed differently in the as_table(), as_ul()) + # and as_p() output of a Form -- their verbose names are not displayed, and a + # separate row is not displayed. They're displayed in the last row of the + # form, directly after that row's form element. + class Person(Form): + first_name = CharField() + last_name = CharField() + hidden_text = CharField(widget=HiddenInput) + birthday = DateField() + + p = Person(auto_id=False) + self.assertEqual(p.as_table(), """<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr> +<tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr> +<tr><th>Birthday:</th><td><input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></td></tr>""") + self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li> +<li>Last name: <input type="text" name="last_name" /></li> +<li>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></li>""") + self.assertEqual(p.as_p(), """<p>First name: <input type="text" name="first_name" /></p> +<p>Last name: <input type="text" name="last_name" /></p> +<p>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></p>""") + + # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label. + p = Person(auto_id='id_%s') + self.assertEqual(p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr> +<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr> +<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></td></tr>""") + self.assertEqual(p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li> +<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li> +<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></li>""") + self.assertEqual(p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p> +<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p> +<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></p>""") + + # If a field with a HiddenInput has errors, the as_table() and as_ul() output + # will include the error message(s) with the text "(Hidden field [fieldname]) " + # prepended. This message is displayed at the top of the output, regardless of + # its field's order in the form. + p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False) + 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> +<tr><th>First name:</th><td><input type="text" name="first_name" value="John" /></td></tr> +<tr><th>Last name:</th><td><input type="text" name="last_name" value="Lennon" /></td></tr> +<tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></td></tr>""") + self.assertEqual(p.as_ul(), """<li><ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul></li> +<li>First name: <input type="text" name="first_name" value="John" /></li> +<li>Last name: <input type="text" name="last_name" value="Lennon" /></li> +<li>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></li>""") + self.assertEqual(p.as_p(), """<ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul> +<p>First name: <input type="text" name="first_name" value="John" /></p> +<p>Last name: <input type="text" name="last_name" value="Lennon" /></p> +<p>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></p>""") + + # A corner case: It's possible for a form to have only HiddenInputs. + class TestForm(Form): + foo = CharField(widget=HiddenInput) + bar = CharField(widget=HiddenInput) + + p = TestForm(auto_id=False) + self.assertEqual(p.as_table(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />') + self.assertEqual(p.as_ul(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />') + self.assertEqual(p.as_p(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />') + + def test_field_order(self): + # A Form's fields are displayed in the same order in which they were defined. + class TestForm(Form): + field1 = CharField() + field2 = CharField() + field3 = CharField() + field4 = CharField() + field5 = CharField() + field6 = CharField() + field7 = CharField() + field8 = CharField() + field9 = CharField() + field10 = CharField() + field11 = CharField() + field12 = CharField() + field13 = CharField() + field14 = CharField() + + p = TestForm(auto_id=False) + self.assertEqual(p.as_table(), """<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr> +<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr> +<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr> +<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr> +<tr><th>Field5:</th><td><input type="text" name="field5" /></td></tr> +<tr><th>Field6:</th><td><input type="text" name="field6" /></td></tr> +<tr><th>Field7:</th><td><input type="text" name="field7" /></td></tr> +<tr><th>Field8:</th><td><input type="text" name="field8" /></td></tr> +<tr><th>Field9:</th><td><input type="text" name="field9" /></td></tr> +<tr><th>Field10:</th><td><input type="text" name="field10" /></td></tr> +<tr><th>Field11:</th><td><input type="text" name="field11" /></td></tr> +<tr><th>Field12:</th><td><input type="text" name="field12" /></td></tr> +<tr><th>Field13:</th><td><input type="text" name="field13" /></td></tr> +<tr><th>Field14:</th><td><input type="text" name="field14" /></td></tr>""") + + def test_form_html_attributes(self): + # Some Field classes have an effect on the HTML attributes of their associated + # Widget. If you set max_length in a CharField and its associated widget is + # either a TextInput or PasswordInput, then the widget's rendered HTML will + # include the "maxlength" attribute. + class UserRegistration(Form): + username = CharField(max_length=10) # uses TextInput by default + password = CharField(max_length=10, widget=PasswordInput) + realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test + address = CharField() # no max_length defined here + + p = UserRegistration(auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li> +<li>Password: <input type="password" name="password" maxlength="10" /></li> +<li>Realname: <input type="text" name="realname" maxlength="10" /></li> +<li>Address: <input type="text" name="address" /></li>""") + + # If you specify a custom "attrs" that includes the "maxlength" attribute, + # the Field's max_length attribute will override whatever "maxlength" you specify + # in "attrs". + class UserRegistration(Form): + username = CharField(max_length=10, widget=TextInput(attrs={'maxlength': 20})) + password = CharField(max_length=10, widget=PasswordInput) + + p = UserRegistration(auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li> +<li>Password: <input type="password" name="password" maxlength="10" /></li>""") + + def test_specifying_labels(self): + # You can specify the label for a field by using the 'label' argument to a Field + # class. If you don't specify 'label', Django will use the field name with + # underscores converted to spaces, and the initial letter capitalized. + class UserRegistration(Form): + username = CharField(max_length=10, label='Your username') + password1 = CharField(widget=PasswordInput) + password2 = CharField(widget=PasswordInput, label='Password (again)') + + p = UserRegistration(auto_id=False) + self.assertEqual(p.as_ul(), """<li>Your username: <input type="text" name="username" maxlength="10" /></li> +<li>Password1: <input type="password" name="password1" /></li> +<li>Password (again): <input type="password" name="password2" /></li>""") + + # Labels for as_* methods will only end in a colon if they don't end in other + # punctuation already. + class Questions(Form): + q1 = CharField(label='The first question') + q2 = CharField(label='What is your name?') + q3 = CharField(label='The answer to life is:') + q4 = CharField(label='Answer this question!') + q5 = CharField(label='The last question. Period.') + + self.assertEqual(Questions(auto_id=False).as_p(), """<p>The first question: <input type="text" name="q1" /></p> +<p>What is your name? <input type="text" name="q2" /></p> +<p>The answer to life is: <input type="text" name="q3" /></p> +<p>Answer this question! <input type="text" name="q4" /></p> +<p>The last question. Period. <input type="text" name="q5" /></p>""") + self.assertEqual(Questions().as_p(), """<p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" /></p> +<p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" /></p> +<p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" /></p> +<p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" /></p> +<p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" /></p>""") + + # A label can be a Unicode object or a bytestring with special characters. + class UserRegistration(Form): + username = CharField(max_length=10, label='ŠĐĆŽćžšđ') + password = CharField(widget=PasswordInput, label=u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111') + + p = UserRegistration(auto_id=False) + 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>') + + # If a label is set to the empty string for a field, that field won't get a label. + class UserRegistration(Form): + username = CharField(max_length=10, label='') + password = CharField(widget=PasswordInput) + + p = UserRegistration(auto_id=False) + self.assertEqual(p.as_ul(), """<li> <input type="text" name="username" maxlength="10" /></li> +<li>Password: <input type="password" name="password" /></li>""") + p = UserRegistration(auto_id='id_%s') + self.assertEqual(p.as_ul(), """<li> <input id="id_username" type="text" name="username" maxlength="10" /></li> +<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>""") + + # If label is None, Django will auto-create the label from the field name. This + # is default behavior. + class UserRegistration(Form): + username = CharField(max_length=10, label=None) + password = CharField(widget=PasswordInput) + + p = UserRegistration(auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /></li> +<li>Password: <input type="password" name="password" /></li>""") + p = UserRegistration(auto_id='id_%s') + self.assertEqual(p.as_ul(), """<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></li> +<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>""") + + def test_label_suffix(self): + # You can specify the 'label_suffix' argument to a Form class to modify the + # punctuation symbol used at the end of a label. By default, the colon (:) is + # used, and is only appended to the label if the label doesn't already end with a + # punctuation symbol: ., !, ? or :. If you specify a different suffix, it will + # be appended regardless of the last character of the label. + class FavoriteForm(Form): + color = CharField(label='Favorite color?') + animal = CharField(label='Favorite animal') + + f = FavoriteForm(auto_id=False) + self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li> +<li>Favorite animal: <input type="text" name="animal" /></li>""") + f = FavoriteForm(auto_id=False, label_suffix='?') + self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li> +<li>Favorite animal? <input type="text" name="animal" /></li>""") + f = FavoriteForm(auto_id=False, label_suffix='') + self.assertEqual(f.as_ul(), """<li>Favorite color? <input type="text" name="color" /></li> +<li>Favorite animal <input type="text" name="animal" /></li>""") + f = FavoriteForm(auto_id=False, label_suffix=u'\u2192') + 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>') + + def test_initial_data(self): + # You can specify initial data for a field by using the 'initial' argument to a + # Field class. This initial data is displayed when a Form is rendered with *no* + # data. It is not displayed when a Form is rendered with any data (including an + # empty dictionary). Also, the initial value is *not* used if data for a + # particular required field isn't provided. + class UserRegistration(Form): + username = CharField(max_length=10, initial='django') + password = CharField(widget=PasswordInput) + + # Here, we're not submitting any data, so the initial value will be displayed.) + p = UserRegistration(auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li> +<li>Password: <input type="password" name="password" /></li>""") + + # Here, we're submitting data, so the initial value will *not* be displayed. + p = UserRegistration({}, auto_id=False) + 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> +<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""") + p = UserRegistration({'username': u''}, auto_id=False) + 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> +<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""") + p = UserRegistration({'username': u'foo'}, auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li> +<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""") + + # An 'initial' value is *not* used as a fallback if data is not provided. In this + # example, we don't provide a value for 'username', and the form raises a + # validation error rather than using the initial value for 'username'. + p = UserRegistration({'password': 'secret'}) + self.assertEqual(p.errors['username'], [u'This field is required.']) + self.assertFalse(p.is_valid()) + + def test_dynamic_initial_data(self): + # The previous technique dealt with "hard-coded" initial data, but it's also + # possible to specify initial data after you've already created the Form class + # (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This + # should be a dictionary containing initial values for one or more fields in the + # form, keyed by field name. + class UserRegistration(Form): + username = CharField(max_length=10) + password = CharField(widget=PasswordInput) + + # Here, we're not submitting any data, so the initial value will be displayed.) + p = UserRegistration(initial={'username': 'django'}, auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li> +<li>Password: <input type="password" name="password" /></li>""") + p = UserRegistration(initial={'username': 'stephane'}, auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li> +<li>Password: <input type="password" name="password" /></li>""") + + # The 'initial' parameter is meaningless if you pass data. + p = UserRegistration({}, initial={'username': 'django'}, auto_id=False) + 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> +<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""") + p = UserRegistration({'username': u''}, initial={'username': 'django'}, auto_id=False) + 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> +<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""") + p = UserRegistration({'username': u'foo'}, initial={'username': 'django'}, auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li> +<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>""") + + # A dynamic 'initial' value is *not* used as a fallback if data is not provided. + # In this example, we don't provide a value for 'username', and the form raises a + # validation error rather than using the initial value for 'username'. + p = UserRegistration({'password': 'secret'}, initial={'username': 'django'}) + self.assertEqual(p.errors['username'], [u'This field is required.']) + self.assertFalse(p.is_valid()) + + # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(), + # then the latter will get precedence. + class UserRegistration(Form): + username = CharField(max_length=10, initial='django') + password = CharField(widget=PasswordInput) + + p = UserRegistration(initial={'username': 'babik'}, auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="babik" maxlength="10" /></li> +<li>Password: <input type="password" name="password" /></li>""") + + def test_callable_initial_data(self): + # The previous technique dealt with raw values as initial data, but it's also + # possible to specify callable data. + class UserRegistration(Form): + username = CharField(max_length=10) + password = CharField(widget=PasswordInput) + options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')]) + + # We need to define functions that get called later.) + def initial_django(): + return 'django' + + def initial_stephane(): + return 'stephane' + + def initial_options(): + return ['f','b'] + + def initial_other_options(): + return ['b','w'] + + # Here, we're not submitting any data, so the initial value will be displayed.) + p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li> +<li>Password: <input type="password" name="password" /></li> +<li>Options: <select multiple="multiple" name="options"> +<option value="f" selected="selected">foo</option> +<option value="b" selected="selected">bar</option> +<option value="w">whiz</option> +</select></li>""") + + # The 'initial' parameter is meaningless if you pass data. + p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False) + 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> +<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> +<li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options"> +<option value="f">foo</option> +<option value="b">bar</option> +<option value="w">whiz</option> +</select></li>""") + p = UserRegistration({'username': u''}, initial={'username': initial_django}, auto_id=False) + 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> +<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> +<li><ul class="errorlist"><li>This field is required.</li></ul>Options: <select multiple="multiple" name="options"> +<option value="f">foo</option> +<option value="b">bar</option> +<option value="w">whiz</option> +</select></li>""") + p = UserRegistration({'username': u'foo', 'options':['f','b']}, initial={'username': initial_django}, auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li> +<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> +<li>Options: <select multiple="multiple" name="options"> +<option value="f" selected="selected">foo</option> +<option value="b" selected="selected">bar</option> +<option value="w">whiz</option> +</select></li>""") + + # A callable 'initial' value is *not* used as a fallback if data is not provided. + # In this example, we don't provide a value for 'username', and the form raises a + # validation error rather than using the initial value for 'username'. + p = UserRegistration({'password': 'secret'}, initial={'username': initial_django, 'options': initial_options}) + self.assertEqual(p.errors['username'], [u'This field is required.']) + self.assertFalse(p.is_valid()) + + # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(), + # then the latter will get precedence. + class UserRegistration(Form): + username = CharField(max_length=10, initial=initial_django) + password = CharField(widget=PasswordInput) + options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')], initial=initial_other_options) + + p = UserRegistration(auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li> +<li>Password: <input type="password" name="password" /></li> +<li>Options: <select multiple="multiple" name="options"> +<option value="f">foo</option> +<option value="b" selected="selected">bar</option> +<option value="w" selected="selected">whiz</option> +</select></li>""") + p = UserRegistration(initial={'username': initial_stephane, 'options': initial_options}, auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li> +<li>Password: <input type="password" name="password" /></li> +<li>Options: <select multiple="multiple" name="options"> +<option value="f" selected="selected">foo</option> +<option value="b" selected="selected">bar</option> +<option value="w">whiz</option> +</select></li>""") + + def test_help_text(self): + # You can specify descriptive text for a field by using the 'help_text' argument) + class UserRegistration(Form): + username = CharField(max_length=10, help_text='e.g., user@example.com') + password = CharField(widget=PasswordInput, help_text='Choose wisely.') + + p = UserRegistration(auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li> +<li>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></li>""") + self.assertEqual(p.as_p(), """<p>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></p> +<p>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></p>""") + 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> +<tr><th>Password:</th><td><input type="password" name="password" /><br /><span class="helptext">Choose wisely.</span></td></tr>""") + + # The help text is displayed whether or not data is provided for the form. + p = UserRegistration({'username': u'foo'}, auto_id=False) + 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> +<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /> <span class="helptext">Choose wisely.</span></li>""") + + # help_text is not displayed for hidden fields. It can be used for documentation + # purposes, though. + class UserRegistration(Form): + username = CharField(max_length=10, help_text='e.g., user@example.com') + password = CharField(widget=PasswordInput) + next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination') + + p = UserRegistration(auto_id=False) + self.assertEqual(p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" /> <span class="helptext">e.g., user@example.com</span></li> +<li>Password: <input type="password" name="password" /><input type="hidden" name="next" value="/" /></li>""") + + # Help text can include arbitrary Unicode characters. + class UserRegistration(Form): + username = CharField(max_length=10, help_text='ŠĐĆŽćžšđ') + + p = UserRegistration(auto_id=False) + 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>') + + def test_subclassing_forms(self): + # You can subclass a Form to add fields. The resulting form subclass will have + # all of the fields of the parent Form, plus whichever fields you define in the + # subclass. + class Person(Form): + first_name = CharField() + last_name = CharField() + birthday = DateField() + + class Musician(Person): + instrument = CharField() + + p = Person(auto_id=False) + self.assertEqual(p.as_ul(), """<li>First name: <input type="text" name="first_name" /></li> +<li>Last name: <input type="text" name="last_name" /></li> +<li>Birthday: <input type="text" name="birthday" /></li>""") + m = Musician(auto_id=False) + self.assertEqual(m.as_ul(), """<li>First name: <input type="text" name="first_name" /></li> +<li>Last name: <input type="text" name="last_name" /></li> +<li>Birthday: <input type="text" name="birthday" /></li> +<li>Instrument: <input type="text" name="instrument" /></li>""") + + # Yes, you can subclass multiple forms. The fields are added in the order in + # which the parent classes are listed. + class Person(Form): + first_name = CharField() + last_name = CharField() + birthday = DateField() + + class Instrument(Form): + instrument = CharField() + + class Beatle(Person, Instrument): + haircut_type = CharField() + + b = Beatle(auto_id=False) + self.assertEqual(b.as_ul(), """<li>First name: <input type="text" name="first_name" /></li> +<li>Last name: <input type="text" name="last_name" /></li> +<li>Birthday: <input type="text" name="birthday" /></li> +<li>Instrument: <input type="text" name="instrument" /></li> +<li>Haircut type: <input type="text" name="haircut_type" /></li>""") + + def test_forms_with_prefixes(self): + # Sometimes it's necessary to have multiple forms display on the same HTML page, + # or multiple copies of the same form. We can accomplish this with form prefixes. + # Pass the keyword argument 'prefix' to the Form constructor to use this feature. + # This value will be prepended to each HTML form field name. One way to think + # about this is "namespaces for HTML forms". Notice that in the data argument, + # each field's key has the prefix, in this case 'person1', prepended to the + # actual field name. + class Person(Form): + first_name = CharField() + last_name = CharField() + birthday = DateField() + + data = { + 'person1-first_name': u'John', + 'person1-last_name': u'Lennon', + 'person1-birthday': u'1940-10-9' + } + p = Person(data, prefix='person1') + 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> +<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> +<li><label for="id_person1-birthday">Birthday:</label> <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" /></li>""") + self.assertEqual(str(p['first_name']), '<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" />') + self.assertEqual(str(p['last_name']), '<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" />') + self.assertEqual(str(p['birthday']), '<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" />') + self.assertEqual(p.errors, {}) + self.assertTrue(p.is_valid()) + self.assertEqual(p.cleaned_data['first_name'], u'John') + self.assertEqual(p.cleaned_data['last_name'], u'Lennon') + self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9)) + + # Let's try submitting some bad data to make sure form.errors and field.errors + # work as expected. + data = { + 'person1-first_name': u'', + 'person1-last_name': u'', + 'person1-birthday': u'' + } + p = Person(data, prefix='person1') + self.assertEqual(p.errors['first_name'], [u'This field is required.']) + self.assertEqual(p.errors['last_name'], [u'This field is required.']) + self.assertEqual(p.errors['birthday'], [u'This field is required.']) + self.assertEqual(p['first_name'].errors, [u'This field is required.']) + try: + p['person1-first_name'].errors + self.fail('Attempts to access non-existent fields should fail.') + except KeyError: + pass + + # In this example, the data doesn't have a prefix, but the form requires it, so + # the form doesn't "see" the fields. + data = { + 'first_name': u'John', + 'last_name': u'Lennon', + 'birthday': u'1940-10-9' + } + p = Person(data, prefix='person1') + self.assertEqual(p.errors['first_name'], [u'This field is required.']) + self.assertEqual(p.errors['last_name'], [u'This field is required.']) + self.assertEqual(p.errors['birthday'], [u'This field is required.']) + + # With prefixes, a single data dictionary can hold data for multiple instances + # of the same form. + data = { + 'person1-first_name': u'John', + 'person1-last_name': u'Lennon', + 'person1-birthday': u'1940-10-9', + 'person2-first_name': u'Jim', + 'person2-last_name': u'Morrison', + 'person2-birthday': u'1943-12-8' + } + p1 = Person(data, prefix='person1') + self.assertTrue(p1.is_valid()) + self.assertEqual(p1.cleaned_data['first_name'], u'John') + self.assertEqual(p1.cleaned_data['last_name'], u'Lennon') + self.assertEqual(p1.cleaned_data['birthday'], datetime.date(1940, 10, 9)) + p2 = Person(data, prefix='person2') + self.assertTrue(p2.is_valid()) + self.assertEqual(p2.cleaned_data['first_name'], u'Jim') + self.assertEqual(p2.cleaned_data['last_name'], u'Morrison') + self.assertEqual(p2.cleaned_data['birthday'], datetime.date(1943, 12, 8)) + + # By default, forms append a hyphen between the prefix and the field name, but a + # form can alter that behavior by implementing the add_prefix() method. This + # method takes a field name and returns the prefixed field, according to + # self.prefix. + class Person(Form): + first_name = CharField() + last_name = CharField() + birthday = DateField() + + def add_prefix(self, field_name): + return self.prefix and '%s-prefix-%s' % (self.prefix, field_name) or field_name + + p = Person(prefix='foo') + 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> +<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> +<li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" /></li>""") + data = { + 'foo-prefix-first_name': u'John', + 'foo-prefix-last_name': u'Lennon', + 'foo-prefix-birthday': u'1940-10-9' + } + p = Person(data, prefix='foo') + self.assertTrue(p.is_valid()) + self.assertEqual(p.cleaned_data['first_name'], u'John') + self.assertEqual(p.cleaned_data['last_name'], u'Lennon') + self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9)) + + def test_forms_with_null_boolean(self): + # NullBooleanField is a bit of a special case because its presentation (widget) + # is different than its data. This is handled transparently, though. + class Person(Form): + name = CharField() + is_cool = NullBooleanField() + + p = Person({'name': u'Joe'}, auto_id=False) + self.assertEqual(str(p['is_cool']), """<select name="is_cool"> +<option value="1" selected="selected">Unknown</option> +<option value="2">Yes</option> +<option value="3">No</option> +</select>""") + p = Person({'name': u'Joe', 'is_cool': u'1'}, auto_id=False) + self.assertEqual(str(p['is_cool']), """<select name="is_cool"> +<option value="1" selected="selected">Unknown</option> +<option value="2">Yes</option> +<option value="3">No</option> +</select>""") + p = Person({'name': u'Joe', 'is_cool': u'2'}, auto_id=False) + self.assertEqual(str(p['is_cool']), """<select name="is_cool"> +<option value="1">Unknown</option> +<option value="2" selected="selected">Yes</option> +<option value="3">No</option> +</select>""") + p = Person({'name': u'Joe', 'is_cool': u'3'}, auto_id=False) + self.assertEqual(str(p['is_cool']), """<select name="is_cool"> +<option value="1">Unknown</option> +<option value="2">Yes</option> +<option value="3" selected="selected">No</option> +</select>""") + p = Person({'name': u'Joe', 'is_cool': True}, auto_id=False) + self.assertEqual(str(p['is_cool']), """<select name="is_cool"> +<option value="1">Unknown</option> +<option value="2" selected="selected">Yes</option> +<option value="3">No</option> +</select>""") + p = Person({'name': u'Joe', 'is_cool': False}, auto_id=False) + self.assertEqual(str(p['is_cool']), """<select name="is_cool"> +<option value="1">Unknown</option> +<option value="2">Yes</option> +<option value="3" selected="selected">No</option> +</select>""") + + def test_forms_with_file_fields(self): + # FileFields are a special case because they take their data from the request.FILES, + # not request.POST. + class FileForm(Form): + file1 = FileField() + + f = FileForm(auto_id=False) + self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>') + + f = FileForm(data={}, files={}, auto_id=False) + 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>') + + f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', '')}, auto_id=False) + 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>') + + f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False) + 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>') + + f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', 'some content')}, auto_id=False) + self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>') + self.assertTrue(f.is_valid()) + + f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')}, auto_id=False) + self.assertEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>') + + def test_basic_processing_in_view(self): + class UserRegistration(Form): + username = CharField(max_length=10) + password1 = CharField(widget=PasswordInput) + password2 = CharField(widget=PasswordInput) + + def clean(self): + if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: + raise ValidationError(u'Please make sure your passwords match.') + + return self.cleaned_data + + def my_function(method, post_data): + if method == 'POST': + form = UserRegistration(post_data, auto_id=False) + else: + form = UserRegistration(auto_id=False) + + if form.is_valid(): + return 'VALID: %r' % form.cleaned_data + + t = Template('<form action="" method="post">\n<table>\n{{ form }}\n</table>\n<input type="submit" />\n</form>') + return t.render(Context({'form': form})) + + # Case 1: GET (an empty form, with no errors).) + self.assertEqual(my_function('GET', {}), """<form action="" method="post"> +<table> +<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" /></td></tr> +<tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr> +<tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr> +</table> +<input type="submit" /> +</form>""") + # Case 2: POST with erroneous data (a redisplayed form, with errors).) + self.assertEqual(my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}), """<form action="" method="post"> +<table> +<tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr> +<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> +<tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr> +<tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr> +</table> +<input type="submit" /> +</form>""") + # Case 3: POST with valid data (the success message).) + self.assertEqual(my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}), "VALID: {'username': u'adrian', 'password1': u'secret', 'password2': u'secret'}") + + def test_templates_with_forms(self): + class UserRegistration(Form): + username = CharField(max_length=10, help_text="Good luck picking a username that doesn't already exist.") + password1 = CharField(widget=PasswordInput) + password2 = CharField(widget=PasswordInput) + + def clean(self): + if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']: + raise ValidationError(u'Please make sure your passwords match.') + + return self.cleaned_data + + # You have full flexibility in displaying form fields in a template. Just pass a + # Form instance to the template, and use "dot" access to refer to individual + # fields. Note, however, that this flexibility comes with the responsibility of + # displaying all the errors, including any that might not be associated with a + # particular field. + t = Template('''<form action=""> +{{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p> +{{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p> +{{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p> +<input type="submit" /> +</form>''') + self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action=""> +<p><label>Your username: <input type="text" name="username" maxlength="10" /></label></p> +<p><label>Password: <input type="password" name="password1" /></label></p> +<p><label>Password (again): <input type="password" name="password2" /></label></p> +<input type="submit" /> +</form>""") + self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})), """<form action=""> +<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p> +<ul class="errorlist"><li>This field is required.</li></ul><p><label>Password: <input type="password" name="password1" /></label></p> +<ul class="errorlist"><li>This field is required.</li></ul><p><label>Password (again): <input type="password" name="password2" /></label></p> +<input type="submit" /> +</form>""") + + # Use form.[field].label to output a field's label. You can specify the label for + # a field by using the 'label' argument to a Field class. If you don't specify + # 'label', Django will use the field name with underscores converted to spaces, + # and the initial letter capitalized. + t = Template('''<form action=""> +<p><label>{{ form.username.label }}: {{ form.username }}</label></p> +<p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p> +<p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p> +<input type="submit" /> +</form>''') + self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action=""> +<p><label>Username: <input type="text" name="username" maxlength="10" /></label></p> +<p><label>Password1: <input type="password" name="password1" /></label></p> +<p><label>Password2: <input type="password" name="password2" /></label></p> +<input type="submit" /> +</form>""") + + # User form.[field].label_tag to output a field's label with a <label> tag + # wrapped around it, but *only* if the given field has an "id" attribute. + # Recall from above that passing the "auto_id" argument to a Form gives each + # field an "id" attribute. + t = Template('''<form action=""> +<p>{{ form.username.label_tag }}: {{ form.username }}</p> +<p>{{ form.password1.label_tag }}: {{ form.password1 }}</p> +<p>{{ form.password2.label_tag }}: {{ form.password2 }}</p> +<input type="submit" /> +</form>''') + self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action=""> +<p>Username: <input type="text" name="username" maxlength="10" /></p> +<p>Password1: <input type="password" name="password1" /></p> +<p>Password2: <input type="password" name="password2" /></p> +<input type="submit" /> +</form>""") + self.assertEqual(t.render(Context({'form': UserRegistration(auto_id='id_%s')})), """<form action=""> +<p><label for="id_username">Username</label>: <input id="id_username" type="text" name="username" maxlength="10" /></p> +<p><label for="id_password1">Password1</label>: <input type="password" name="password1" id="id_password1" /></p> +<p><label for="id_password2">Password2</label>: <input type="password" name="password2" id="id_password2" /></p> +<input type="submit" /> +</form>""") + + # User form.[field].help_text to output a field's help text. If the given field + # does not have help text, nothing will be output. + t = Template('''<form action=""> +<p>{{ form.username.label_tag }}: {{ form.username }}<br />{{ form.username.help_text }}</p> +<p>{{ form.password1.label_tag }}: {{ form.password1 }}</p> +<p>{{ form.password2.label_tag }}: {{ form.password2 }}</p> +<input type="submit" /> +</form>''') + self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """<form action=""> +<p>Username: <input type="text" name="username" maxlength="10" /><br />Good luck picking a username that doesn't already exist.</p> +<p>Password1: <input type="password" name="password1" /></p> +<p>Password2: <input type="password" name="password2" /></p> +<input type="submit" /> +</form>""") + self.assertEqual(Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})), u'') + + # The label_tag() method takes an optional attrs argument: a dictionary of HTML + # attributes to add to the <label> tag. + f = UserRegistration(auto_id='id_%s') + form_output = [] + + for bf in f: + form_output.append(bf.label_tag(attrs={'class': 'pretty'})) + + self.assertEqual(form_output, [ + '<label for="id_username" class="pretty">Username</label>', + '<label for="id_password1" class="pretty">Password1</label>', + '<label for="id_password2" class="pretty">Password2</label>', + ]) + + # To display the errors that aren't associated with a particular field -- e.g., + # the errors caused by Form.clean() -- use {{ form.non_field_errors }} in the + # template. If used on its own, it is displayed as a <ul> (or an empty string, if + # the list of errors is empty). You can also use it in {% if %} statements. + t = Template('''<form action=""> +{{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p> +{{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p> +{{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p> +<input type="submit" /> +</form>''') + self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """<form action=""> +<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p> +<p><label>Password: <input type="password" name="password1" /></label></p> +<p><label>Password (again): <input type="password" name="password2" /></label></p> +<input type="submit" /> +</form>""") + t = Template('''<form action=""> +{{ form.non_field_errors }} +{{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p> +{{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p> +{{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p> +<input type="submit" /> +</form>''') + self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """<form action=""> +<ul class="errorlist"><li>Please make sure your passwords match.</li></ul> +<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p> +<p><label>Password: <input type="password" name="password1" /></label></p> +<p><label>Password (again): <input type="password" name="password2" /></label></p> +<input type="submit" /> +</form>""") + + def test_empty_permitted(self): + # Sometimes (pretty much in formsets) we want to allow a form to pass validation + # if it is completely empty. We can accomplish this by using the empty_permitted + # agrument to a form constructor. + class SongForm(Form): + artist = CharField() + name = CharField() + + # First let's show what happens id empty_permitted=False (the default): + data = {'artist': '', 'song': ''} + form = SongForm(data, empty_permitted=False) + self.assertFalse(form.is_valid()) + self.assertEqual(form.errors, {'name': [u'This field is required.'], 'artist': [u'This field is required.']}) + try: + form.cleaned_data + self.fail('Attempts to access cleaned_data when validation fails should fail.') + except AttributeError: + pass + + # Now let's show what happens when empty_permitted=True and the form is empty. + form = SongForm(data, empty_permitted=True) + self.assertTrue(form.is_valid()) + self.assertEqual(form.errors, {}) + self.assertEqual(form.cleaned_data, {}) + + # But if we fill in data for one of the fields, the form is no longer empty and + # the whole thing must pass validation. + data = {'artist': 'The Doors', 'song': ''} + form = SongForm(data, empty_permitted=False) + self.assertFalse(form.is_valid()) + self.assertEqual(form.errors, {'name': [u'This field is required.']}) + try: + form.cleaned_data + self.fail('Attempts to access cleaned_data when validation fails should fail.') + except AttributeError: + pass + + # If a field is not given in the data then None is returned for its data. Lets + # make sure that when checking for empty_permitted that None is treated + # accordingly. + data = {'artist': None, 'song': ''} + form = SongForm(data, empty_permitted=True) + self.assertTrue(form.is_valid()) + + # However, we *really* need to be sure we are checking for None as any data in + # initial that returns False on a boolean call needs to be treated literally. + class PriceForm(Form): + amount = FloatField() + qty = IntegerField() + + data = {'amount': '0.0', 'qty': ''} + form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True) + self.assertTrue(form.is_valid()) + + def test_extracting_hidden_and_visible(self): + class SongForm(Form): + token = CharField(widget=HiddenInput) + artist = CharField() + name = CharField() + + form = SongForm() + self.assertEqual([f.name for f in form.hidden_fields()], ['token']) + self.assertEqual([f.name for f in form.visible_fields()], ['artist', 'name']) + + def test_hidden_initial_gets_id(self): + class MyForm(Form): + field1 = CharField(max_length=50, show_hidden_initial=True) + + 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>') + + def test_error_html_required_html_classes(self): + class Person(Form): + name = CharField() + is_cool = NullBooleanField() + email = EmailField(required=False) + age = IntegerField() + + p = Person({}) + p.error_css_class = 'error' + p.required_css_class = 'required' + + 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> +<li class="required"><label for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> +<option value="1" selected="selected">Unknown</option> +<option value="2">Yes</option> +<option value="3">No</option> +</select></li> +<li><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></li> +<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>""") + + self.assertEqual(p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul> +<p class="required error"><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p> +<p class="required"><label for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> +<option value="1" selected="selected">Unknown</option> +<option value="2">Yes</option> +<option value="3">No</option> +</select></p> +<p><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></p> +<ul class="errorlist"><li>This field is required.</li></ul> +<p class="required error"><label for="id_age">Age:</label> <input type="text" name="age" id="id_age" /></p>""") + + 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> +<tr class="required"><th><label for="id_is_cool">Is cool:</label></th><td><select name="is_cool" id="id_is_cool"> +<option value="1" selected="selected">Unknown</option> +<option value="2">Yes</option> +<option value="3">No</option> +</select></td></tr> +<tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email" /></td></tr> +<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>""") + + def test_label_split_datetime_not_displayed(self): + class EventForm(Form): + happened_at = SplitDateTimeField(widget=widgets.SplitHiddenDateTimeWidget) + + form = EventForm() + 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" />') diff --git a/tests/regressiontests/forms/tests/formsets.py b/tests/regressiontests/forms/tests/formsets.py new file mode 100644 index 0000000000..bf7124fe59 --- /dev/null +++ b/tests/regressiontests/forms/tests/formsets.py @@ -0,0 +1,797 @@ +# -*- coding: utf-8 -*- +from django.forms import Form, CharField, IntegerField, ValidationError +from django.forms.formsets import formset_factory, BaseFormSet +from django.utils.unittest import TestCase + + +class Choice(Form): + choice = CharField() + votes = IntegerField() + + +# FormSet allows us to use multiple instance of the same form on 1 page. For now, +# the best way to create a FormSet is by using the formset_factory function. +ChoiceFormSet = formset_factory(Choice) + + +class FavoriteDrinkForm(Form): + name = CharField() + + +class BaseFavoriteDrinksFormSet(BaseFormSet): + def clean(self): + seen_drinks = [] + + for drink in self.cleaned_data: + if drink['name'] in seen_drinks: + raise ValidationError('You may only specify a drink once.') + + seen_drinks.append(drink['name']) + + +# Let's define a FormSet that takes a list of favorite drinks, but raises an +# error if there are any duplicates. Used in ``test_clean_hook``, +# ``test_regression_6926`` & ``test_regression_12878``. +FavoriteDrinksFormSet = formset_factory(FavoriteDrinkForm, + formset=BaseFavoriteDrinksFormSet, extra=3) + + +class FormsFormsetTestCase(TestCase): + def test_basic_formset(self): + # A FormSet constructor takes the same arguments as Form. Let's create a FormSet + # for adding data. By default, it displays 1 blank form. It can display more, + # but we'll look at how to do so later. + formset = ChoiceFormSet(auto_id=False, prefix='choices') + self.assertEqual(str(formset), """<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" /> +<tr><th>Choice:</th><td><input type="text" name="choices-0-choice" /></td></tr> +<tr><th>Votes:</th><td><input type="text" name="choices-0-votes" /></td></tr>""") + + # On thing to note is that there needs to be a special value in the data. This + # value tells the FormSet how many forms were displayed so it can tell how + # many forms it needs to clean and validate. You could use javascript to create + # new forms on the client side, but they won't get validated unless you increment + # the TOTAL_FORMS field appropriately. + + data = { + 'choices-TOTAL_FORMS': '1', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-0-choice': 'Calexico', + 'choices-0-votes': '100', + } + # We treat FormSet pretty much like we would treat a normal Form. FormSet has an + # is_valid method, and a cleaned_data or errors attribute depending on whether all + # the forms passed validation. However, unlike a Form instance, cleaned_data and + # errors will be a list of dicts rather than just a single dict. + + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertTrue(formset.is_valid()) + self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': u'Calexico'}]) + + # If a FormSet was not passed any data, its is_valid method should return False. + formset = ChoiceFormSet() + self.assertFalse(formset.is_valid()) + + def test_formset_validation(self): + # FormSet instances can also have an error attribute if validation failed for + # any of the forms. + + data = { + 'choices-TOTAL_FORMS': '1', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-0-choice': 'Calexico', + 'choices-0-votes': '', + } + + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertFalse(formset.is_valid()) + self.assertEqual(formset.errors, [{'votes': [u'This field is required.']}]) + + def test_formset_initial_data(self): + # We can also prefill a FormSet with existing data by providing an ``initial`` + # argument to the constructor. ``initial`` should be a list of dicts. By default, + # an extra blank form is included. + + initial = [{'choice': u'Calexico', 'votes': 100}] + formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') + form_output = [] + + for form in formset.forms: + form_output.append(form.as_ul()) + + self.assertEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> +<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> +<li>Choice: <input type="text" name="choices-1-choice" /></li> +<li>Votes: <input type="text" name="choices-1-votes" /></li>""") + + # Let's simulate what would happen if we submitted this form. + + data = { + 'choices-TOTAL_FORMS': '2', # the number of forms rendered + 'choices-INITIAL_FORMS': '1', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-0-choice': 'Calexico', + 'choices-0-votes': '100', + 'choices-1-choice': '', + 'choices-1-votes': '', + } + + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertTrue(formset.is_valid()) + self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': u'Calexico'}, {}]) + + def test_second_form_partially_filled(self): + # But the second form was blank! Shouldn't we get some errors? No. If we display + # a form as blank, it's ok for it to be submitted as blank. If we fill out even + # one of the fields of a blank form though, it will be validated. We may want to + # required that at least x number of forms are completed, but we'll show how to + # handle that later. + + data = { + 'choices-TOTAL_FORMS': '2', # the number of forms rendered + 'choices-INITIAL_FORMS': '1', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-0-choice': 'Calexico', + 'choices-0-votes': '100', + 'choices-1-choice': 'The Decemberists', + 'choices-1-votes': '', # missing value + } + + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertFalse(formset.is_valid()) + self.assertEqual(formset.errors, [{}, {'votes': [u'This field is required.']}]) + + def test_delete_prefilled_data(self): + # If we delete data that was pre-filled, we should get an error. Simply removing + # data from form fields isn't the proper way to delete it. We'll see how to + # handle that case later. + + data = { + 'choices-TOTAL_FORMS': '2', # the number of forms rendered + 'choices-INITIAL_FORMS': '1', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-0-choice': '', # deleted value + 'choices-0-votes': '', # deleted value + 'choices-1-choice': '', + 'choices-1-votes': '', + } + + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertFalse(formset.is_valid()) + self.assertEqual(formset.errors, [{'votes': [u'This field is required.'], 'choice': [u'This field is required.']}, {}]) + + def test_displaying_more_than_one_blank_form(self): + # Displaying more than 1 blank form ########################################### + # We can also display more than 1 empty form at a time. To do so, pass a + # extra argument to formset_factory. + ChoiceFormSet = formset_factory(Choice, extra=3) + + formset = ChoiceFormSet(auto_id=False, prefix='choices') + form_output = [] + + for form in formset.forms: + form_output.append(form.as_ul()) + + self.assertEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" /></li> +<li>Votes: <input type="text" name="choices-0-votes" /></li> +<li>Choice: <input type="text" name="choices-1-choice" /></li> +<li>Votes: <input type="text" name="choices-1-votes" /></li> +<li>Choice: <input type="text" name="choices-2-choice" /></li> +<li>Votes: <input type="text" name="choices-2-votes" /></li>""") + + # Since we displayed every form as blank, we will also accept them back as blank. + # This may seem a little strange, but later we will show how to require a minimum + # number of forms to be completed. + + data = { + 'choices-TOTAL_FORMS': '3', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-0-choice': '', + 'choices-0-votes': '', + 'choices-1-choice': '', + 'choices-1-votes': '', + 'choices-2-choice': '', + 'choices-2-votes': '', + } + + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertTrue(formset.is_valid()) + self.assertEqual([form.cleaned_data for form in formset.forms], [{}, {}, {}]) + + def test_single_form_completed(self): + # We can just fill out one of the forms. + + data = { + 'choices-TOTAL_FORMS': '3', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-0-choice': 'Calexico', + 'choices-0-votes': '100', + 'choices-1-choice': '', + 'choices-1-votes': '', + 'choices-2-choice': '', + 'choices-2-votes': '', + } + + ChoiceFormSet = formset_factory(Choice, extra=3) + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertTrue(formset.is_valid()) + self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': u'Calexico'}, {}, {}]) + + def test_second_form_partially_filled_2(self): + # And once again, if we try to partially complete a form, validation will fail. + + data = { + 'choices-TOTAL_FORMS': '3', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-0-choice': 'Calexico', + 'choices-0-votes': '100', + 'choices-1-choice': 'The Decemberists', + 'choices-1-votes': '', # missing value + 'choices-2-choice': '', + 'choices-2-votes': '', + } + + ChoiceFormSet = formset_factory(Choice, extra=3) + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertFalse(formset.is_valid()) + self.assertEqual(formset.errors, [{}, {'votes': [u'This field is required.']}, {}]) + + def test_more_initial_data(self): + # The extra argument also works when the formset is pre-filled with initial + # data. + + data = { + 'choices-TOTAL_FORMS': '3', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-0-choice': 'Calexico', + 'choices-0-votes': '100', + 'choices-1-choice': '', + 'choices-1-votes': '', # missing value + 'choices-2-choice': '', + 'choices-2-votes': '', + } + + initial = [{'choice': u'Calexico', 'votes': 100}] + ChoiceFormSet = formset_factory(Choice, extra=3) + formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') + form_output = [] + + for form in formset.forms: + form_output.append(form.as_ul()) + + self.assertEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> +<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> +<li>Choice: <input type="text" name="choices-1-choice" /></li> +<li>Votes: <input type="text" name="choices-1-votes" /></li> +<li>Choice: <input type="text" name="choices-2-choice" /></li> +<li>Votes: <input type="text" name="choices-2-votes" /></li> +<li>Choice: <input type="text" name="choices-3-choice" /></li> +<li>Votes: <input type="text" name="choices-3-votes" /></li>""") + + # Make sure retrieving an empty form works, and it shows up in the form list + + self.assertTrue(formset.empty_form.empty_permitted) + self.assertEqual(formset.empty_form.as_ul(), """<li>Choice: <input type="text" name="choices-__prefix__-choice" /></li> +<li>Votes: <input type="text" name="choices-__prefix__-votes" /></li>""") + + def test_formset_with_deletion(self): + # FormSets with deletion ###################################################### + # We can easily add deletion ability to a FormSet with an argument to + # formset_factory. This will add a boolean field to each form instance. When + # that boolean field is True, the form will be in formset.deleted_forms + + ChoiceFormSet = formset_factory(Choice, can_delete=True) + + initial = [{'choice': u'Calexico', 'votes': 100}, {'choice': u'Fergie', 'votes': 900}] + formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') + form_output = [] + + for form in formset.forms: + form_output.append(form.as_ul()) + + self.assertEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> +<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> +<li>Delete: <input type="checkbox" name="choices-0-DELETE" /></li> +<li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li> +<li>Votes: <input type="text" name="choices-1-votes" value="900" /></li> +<li>Delete: <input type="checkbox" name="choices-1-DELETE" /></li> +<li>Choice: <input type="text" name="choices-2-choice" /></li> +<li>Votes: <input type="text" name="choices-2-votes" /></li> +<li>Delete: <input type="checkbox" name="choices-2-DELETE" /></li>""") + + # To delete something, we just need to set that form's special delete field to + # 'on'. Let's go ahead and delete Fergie. + + data = { + 'choices-TOTAL_FORMS': '3', # the number of forms rendered + 'choices-INITIAL_FORMS': '2', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-0-choice': 'Calexico', + 'choices-0-votes': '100', + 'choices-0-DELETE': '', + 'choices-1-choice': 'Fergie', + 'choices-1-votes': '900', + 'choices-1-DELETE': 'on', + 'choices-2-choice': '', + 'choices-2-votes': '', + 'choices-2-DELETE': '', + } + + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertTrue(formset.is_valid()) + self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'DELETE': False, 'choice': u'Calexico'}, {'votes': 900, 'DELETE': True, 'choice': u'Fergie'}, {}]) + self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'choice': u'Fergie'}]) + + # If we fill a form with something and then we check the can_delete checkbox for + # that form, that form's errors should not make the entire formset invalid since + # it's going to be deleted. + + class CheckForm(Form): + field = IntegerField(min_value=100) + + data = { + 'check-TOTAL_FORMS': '3', # the number of forms rendered + 'check-INITIAL_FORMS': '2', # the number of forms with initial data + 'check-MAX_NUM_FORMS': '0', # max number of forms + 'check-0-field': '200', + 'check-0-DELETE': '', + 'check-1-field': '50', + 'check-1-DELETE': 'on', + 'check-2-field': '', + 'check-2-DELETE': '', + } + CheckFormSet = formset_factory(CheckForm, can_delete=True) + formset = CheckFormSet(data, prefix='check') + self.assertTrue(formset.is_valid()) + + # If we remove the deletion flag now we will have our validation back. + data['check-1-DELETE'] = '' + formset = CheckFormSet(data, prefix='check') + self.assertFalse(formset.is_valid()) + + # Should be able to get deleted_forms from a valid formset even if a + # deleted form would have been invalid. + + class Person(Form): + name = CharField() + + PeopleForm = formset_factory( + form=Person, + can_delete=True) + + p = PeopleForm( + {'form-0-name': u'', 'form-0-DELETE': u'on', # no name! + 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, + 'form-MAX_NUM_FORMS': 1}) + + self.assertTrue(p.is_valid()) + self.assertEqual(len(p.deleted_forms), 1) + + def test_formsets_with_ordering(self): + # FormSets with ordering ###################################################### + # We can also add ordering ability to a FormSet with an argument to + # formset_factory. This will add a integer field to each form instance. When + # form validation succeeds, [form.cleaned_data for form in formset.forms] will have the data in the correct + # order specified by the ordering fields. If a number is duplicated in the set + # of ordering fields, for instance form 0 and form 3 are both marked as 1, then + # the form index used as a secondary ordering criteria. In order to put + # something at the front of the list, you'd need to set it's order to 0. + + ChoiceFormSet = formset_factory(Choice, can_order=True) + + initial = [{'choice': u'Calexico', 'votes': 100}, {'choice': u'Fergie', 'votes': 900}] + formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') + form_output = [] + + for form in formset.forms: + form_output.append(form.as_ul()) + + self.assertEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> +<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> +<li>Order: <input type="text" name="choices-0-ORDER" value="1" /></li> +<li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li> +<li>Votes: <input type="text" name="choices-1-votes" value="900" /></li> +<li>Order: <input type="text" name="choices-1-ORDER" value="2" /></li> +<li>Choice: <input type="text" name="choices-2-choice" /></li> +<li>Votes: <input type="text" name="choices-2-votes" /></li> +<li>Order: <input type="text" name="choices-2-ORDER" /></li>""") + + data = { + 'choices-TOTAL_FORMS': '3', # the number of forms rendered + 'choices-INITIAL_FORMS': '2', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-0-choice': 'Calexico', + 'choices-0-votes': '100', + 'choices-0-ORDER': '1', + 'choices-1-choice': 'Fergie', + 'choices-1-votes': '900', + 'choices-1-ORDER': '2', + 'choices-2-choice': 'The Decemberists', + 'choices-2-votes': '500', + 'choices-2-ORDER': '0', + } + + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertTrue(formset.is_valid()) + form_output = [] + + for form in formset.ordered_forms: + form_output.append(form.cleaned_data) + + self.assertEqual(form_output, [ + {'votes': 500, 'ORDER': 0, 'choice': u'The Decemberists'}, + {'votes': 100, 'ORDER': 1, 'choice': u'Calexico'}, + {'votes': 900, 'ORDER': 2, 'choice': u'Fergie'}, + ]) + + def test_empty_ordered_fields(self): + # Ordering fields are allowed to be left blank, and if they *are* left blank, + # they will be sorted below everything else. + + data = { + 'choices-TOTAL_FORMS': '4', # the number of forms rendered + 'choices-INITIAL_FORMS': '3', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-0-choice': 'Calexico', + 'choices-0-votes': '100', + 'choices-0-ORDER': '1', + 'choices-1-choice': 'Fergie', + 'choices-1-votes': '900', + 'choices-1-ORDER': '2', + 'choices-2-choice': 'The Decemberists', + 'choices-2-votes': '500', + 'choices-2-ORDER': '', + 'choices-3-choice': 'Basia Bulat', + 'choices-3-votes': '50', + 'choices-3-ORDER': '', + } + + ChoiceFormSet = formset_factory(Choice, can_order=True) + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertTrue(formset.is_valid()) + form_output = [] + + for form in formset.ordered_forms: + form_output.append(form.cleaned_data) + + self.assertEqual(form_output, [ + {'votes': 100, 'ORDER': 1, 'choice': u'Calexico'}, + {'votes': 900, 'ORDER': 2, 'choice': u'Fergie'}, + {'votes': 500, 'ORDER': None, 'choice': u'The Decemberists'}, + {'votes': 50, 'ORDER': None, 'choice': u'Basia Bulat'}, + ]) + + def test_ordering_blank_fieldsets(self): + # Ordering should work with blank fieldsets. + + data = { + 'choices-TOTAL_FORMS': '3', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + } + + ChoiceFormSet = formset_factory(Choice, can_order=True) + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertTrue(formset.is_valid()) + form_output = [] + + for form in formset.ordered_forms: + form_output.append(form.cleaned_data) + + self.assertEqual(form_output, []) + + def test_formset_with_ordering_and_deletion(self): + # FormSets with ordering + deletion ########################################### + # Let's try throwing ordering and deletion into the same form. + + ChoiceFormSet = formset_factory(Choice, can_order=True, can_delete=True) + + initial = [ + {'choice': u'Calexico', 'votes': 100}, + {'choice': u'Fergie', 'votes': 900}, + {'choice': u'The Decemberists', 'votes': 500}, + ] + formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') + form_output = [] + + for form in formset.forms: + form_output.append(form.as_ul()) + + self.assertEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> +<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li> +<li>Order: <input type="text" name="choices-0-ORDER" value="1" /></li> +<li>Delete: <input type="checkbox" name="choices-0-DELETE" /></li> +<li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li> +<li>Votes: <input type="text" name="choices-1-votes" value="900" /></li> +<li>Order: <input type="text" name="choices-1-ORDER" value="2" /></li> +<li>Delete: <input type="checkbox" name="choices-1-DELETE" /></li> +<li>Choice: <input type="text" name="choices-2-choice" value="The Decemberists" /></li> +<li>Votes: <input type="text" name="choices-2-votes" value="500" /></li> +<li>Order: <input type="text" name="choices-2-ORDER" value="3" /></li> +<li>Delete: <input type="checkbox" name="choices-2-DELETE" /></li> +<li>Choice: <input type="text" name="choices-3-choice" /></li> +<li>Votes: <input type="text" name="choices-3-votes" /></li> +<li>Order: <input type="text" name="choices-3-ORDER" /></li> +<li>Delete: <input type="checkbox" name="choices-3-DELETE" /></li>""") + + # Let's delete Fergie, and put The Decemberists ahead of Calexico. + + data = { + 'choices-TOTAL_FORMS': '4', # the number of forms rendered + 'choices-INITIAL_FORMS': '3', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-0-choice': 'Calexico', + 'choices-0-votes': '100', + 'choices-0-ORDER': '1', + 'choices-0-DELETE': '', + 'choices-1-choice': 'Fergie', + 'choices-1-votes': '900', + 'choices-1-ORDER': '2', + 'choices-1-DELETE': 'on', + 'choices-2-choice': 'The Decemberists', + 'choices-2-votes': '500', + 'choices-2-ORDER': '0', + 'choices-2-DELETE': '', + 'choices-3-choice': '', + 'choices-3-votes': '', + 'choices-3-ORDER': '', + 'choices-3-DELETE': '', + } + + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertTrue(formset.is_valid()) + form_output = [] + + for form in formset.ordered_forms: + form_output.append(form.cleaned_data) + + self.assertEqual(form_output, [ + {'votes': 500, 'DELETE': False, 'ORDER': 0, 'choice': u'The Decemberists'}, + {'votes': 100, 'DELETE': False, 'ORDER': 1, 'choice': u'Calexico'}, + ]) + self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': u'Fergie'}]) + + def test_invalid_deleted_form_with_ordering(self): + # Should be able to get ordered forms from a valid formset even if a + # deleted form would have been invalid. + + class Person(Form): + name = CharField() + + PeopleForm = formset_factory(form=Person, can_delete=True, can_order=True) + + p = PeopleForm({ + 'form-0-name': u'', + 'form-0-DELETE': u'on', # no name! + 'form-TOTAL_FORMS': 1, + 'form-INITIAL_FORMS': 1, + 'form-MAX_NUM_FORMS': 1 + }) + + self.assertTrue(p.is_valid()) + self.assertEqual(p.ordered_forms, []) + + def test_clean_hook(self): + # FormSet clean hook ########################################################## + # FormSets have a hook for doing extra validation that shouldn't be tied to any + # particular form. It follows the same pattern as the clean hook on Forms. + + # We start out with a some duplicate data. + + data = { + 'drinks-TOTAL_FORMS': '2', # the number of forms rendered + 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data + 'drinks-MAX_NUM_FORMS': '0', # max number of forms + 'drinks-0-name': 'Gin and Tonic', + 'drinks-1-name': 'Gin and Tonic', + } + + formset = FavoriteDrinksFormSet(data, prefix='drinks') + self.assertFalse(formset.is_valid()) + + # Any errors raised by formset.clean() are available via the + # formset.non_form_errors() method. + + for error in formset.non_form_errors(): + self.assertEqual(str(error), 'You may only specify a drink once.') + + # Make sure we didn't break the valid case. + + data = { + 'drinks-TOTAL_FORMS': '2', # the number of forms rendered + 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data + 'drinks-MAX_NUM_FORMS': '0', # max number of forms + 'drinks-0-name': 'Gin and Tonic', + 'drinks-1-name': 'Bloody Mary', + } + + formset = FavoriteDrinksFormSet(data, prefix='drinks') + self.assertTrue(formset.is_valid()) + self.assertEqual(formset.non_form_errors(), []) + + def test_limiting_max_forms(self): + # Limiting the maximum number of forms ######################################## + # Base case for max_num. + + # When not passed, max_num will take its default value of None, i.e. unlimited + # number of forms, only controlled by the value of the extra parameter. + + LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3) + formset = LimitedFavoriteDrinkFormSet() + form_output = [] + + for form in formset.forms: + form_output.append(str(form)) + + self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr> +<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr> +<tr><th><label for="id_form-2-name">Name:</label></th><td><input type="text" name="form-2-name" id="id_form-2-name" /></td></tr>""") + + # If max_num is 0 then no form is rendered at all. + LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=0) + formset = LimitedFavoriteDrinkFormSet() + form_output = [] + + for form in formset.forms: + form_output.append(str(form)) + + self.assertEqual('\n'.join(form_output), "") + + LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=5, max_num=2) + formset = LimitedFavoriteDrinkFormSet() + form_output = [] + + for form in formset.forms: + form_output.append(str(form)) + + self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr> +<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""") + + # Ensure that max_num has no effect when extra is less than max_num. + + LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2) + formset = LimitedFavoriteDrinkFormSet() + form_output = [] + + for form in formset.forms: + form_output.append(str(form)) + + self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>""") + + def test_max_num_with_initial_data(self): + # max_num with initial data + + # When not passed, max_num will take its default value of None, i.e. unlimited + # number of forms, only controlled by the values of the initial and extra + # parameters. + + initial = [ + {'name': 'Fernet and Coke'}, + ] + LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1) + formset = LimitedFavoriteDrinkFormSet(initial=initial) + form_output = [] + + for form in formset.forms: + form_output.append(str(form)) + + self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Fernet and Coke" id="id_form-0-name" /></td></tr> +<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""") + + def test_max_num_zero(self): + # If max_num is 0 then no form is rendered at all, even if extra and initial + # are specified. + + initial = [ + {'name': 'Fernet and Coke'}, + {'name': 'Bloody Mary'}, + ] + LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=0) + formset = LimitedFavoriteDrinkFormSet(initial=initial) + form_output = [] + + for form in formset.forms: + form_output.append(str(form)) + + self.assertEqual('\n'.join(form_output), "") + + def test_more_initial_than_max_num(self): + # More initial forms than max_num will result in only the first max_num of + # them to be displayed with no extra forms. + + initial = [ + {'name': 'Gin Tonic'}, + {'name': 'Bloody Mary'}, + {'name': 'Jack and Coke'}, + ] + LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2) + formset = LimitedFavoriteDrinkFormSet(initial=initial) + form_output = [] + + for form in formset.forms: + form_output.append(str(form)) + + self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name" /></td></tr> +<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" value="Bloody Mary" id="id_form-1-name" /></td></tr>""") + + # One form from initial and extra=3 with max_num=2 should result in the one + # initial form and one extra. + initial = [ + {'name': 'Gin Tonic'}, + ] + LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=2) + formset = LimitedFavoriteDrinkFormSet(initial=initial) + form_output = [] + + for form in formset.forms: + form_output.append(str(form)) + + self.assertEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name" /></td></tr> +<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""") + + def test_regression_6926(self): + # Regression test for #6926 ################################################## + # Make sure the management form has the correct prefix. + + formset = FavoriteDrinksFormSet() + self.assertEqual(formset.management_form.prefix, 'form') + + formset = FavoriteDrinksFormSet(data={}) + self.assertEqual(formset.management_form.prefix, 'form') + + formset = FavoriteDrinksFormSet(initial={}) + self.assertEqual(formset.management_form.prefix, 'form') + + def test_regression_12878(self): + # Regression test for #12878 ################################################# + + data = { + 'drinks-TOTAL_FORMS': '2', # the number of forms rendered + 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data + 'drinks-MAX_NUM_FORMS': '0', # max number of forms + 'drinks-0-name': 'Gin and Tonic', + 'drinks-1-name': 'Gin and Tonic', + } + + formset = FavoriteDrinksFormSet(data, prefix='drinks') + self.assertFalse(formset.is_valid()) + self.assertEqual(formset.non_form_errors(), [u'You may only specify a drink once.']) + + +data = { + 'choices-TOTAL_FORMS': '1', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-0-choice': 'Calexico', + 'choices-0-votes': '100', +} + +class Choice(Form): + choice = CharField() + votes = IntegerField() + +ChoiceFormSet = formset_factory(Choice) + +class FormsetAsFooTests(TestCase): + def test_as_table(self): + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertEqual(formset.as_table(),"""<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> +<tr><th>Choice:</th><td><input type="text" name="choices-0-choice" value="Calexico" /></td></tr> +<tr><th>Votes:</th><td><input type="text" name="choices-0-votes" value="100" /></td></tr>""") + + def test_as_p(self): + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertEqual(formset.as_p(),"""<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> +<p>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></p> +<p>Votes: <input type="text" name="choices-0-votes" value="100" /></p>""") + + def test_as_ul(self): + formset = ChoiceFormSet(data, auto_id=False, prefix='choices') + self.assertEqual(formset.as_ul(),"""<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> +<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> +<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li>""") diff --git a/tests/regressiontests/forms/input_formats.py b/tests/regressiontests/forms/tests/input_formats.py similarity index 100% rename from tests/regressiontests/forms/input_formats.py rename to tests/regressiontests/forms/tests/input_formats.py diff --git a/tests/regressiontests/forms/tests/media.py b/tests/regressiontests/forms/tests/media.py new file mode 100644 index 0000000000..9a552a31da --- /dev/null +++ b/tests/regressiontests/forms/tests/media.py @@ -0,0 +1,460 @@ +# -*- coding: utf-8 -*- +from django.conf import settings +from django.forms import TextInput, Media, TextInput, CharField, Form, MultiWidget +from django.utils.unittest import TestCase + + +class FormsMediaTestCase(TestCase): + # Tests for the media handling on widgets and forms + def setUp(self): + super(FormsMediaTestCase, self).setUp() + self.original_media_url = settings.MEDIA_URL + settings.MEDIA_URL = 'http://media.example.com/media/' + + def tearDown(self): + settings.MEDIA_URL = self.original_media_url + super(FormsMediaTestCase, self).tearDown() + + def test_construction(self): + # Check construction of media objects + m = Media(css={'all': ('path/to/css1','/path/to/css2')}, js=('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3')) + self.assertEqual(str(m), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") + + class Foo: + css = { + 'all': ('path/to/css1','/path/to/css2') + } + js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') + + m3 = Media(Foo) + self.assertEqual(str(m3), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") + + # A widget can exist without a media definition + class MyWidget(TextInput): + pass + + w = MyWidget() + self.assertEqual(str(w.media), '') + + def test_media_dsl(self): + ############################################################### + # DSL Class-based media definitions + ############################################################### + + # A widget can define media if it needs to. + # Any absolute path will be preserved; relative paths are combined + # with the value of settings.MEDIA_URL + class MyWidget1(TextInput): + class Media: + css = { + 'all': ('path/to/css1','/path/to/css2') + } + js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') + + w1 = MyWidget1() + self.assertEqual(str(w1.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") + + # Media objects can be interrogated by media type + self.assertEqual(str(w1.media['css']), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />""") + + self.assertEqual(str(w1.media['js']), """<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") + + def test_combine_media(self): + # Media objects can be combined. Any given media resource will appear only + # once. Duplicated media definitions are ignored. + class MyWidget1(TextInput): + class Media: + css = { + 'all': ('path/to/css1','/path/to/css2') + } + js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') + + class MyWidget2(TextInput): + class Media: + css = { + 'all': ('/path/to/css2','/path/to/css3') + } + js = ('/path/to/js1','/path/to/js4') + + class MyWidget3(TextInput): + class Media: + css = { + 'all': ('/path/to/css3','path/to/css1') + } + js = ('/path/to/js1','/path/to/js4') + + w1 = MyWidget1() + w2 = MyWidget2() + w3 = MyWidget3() + self.assertEqual(str(w1.media + w2.media + w3.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> +<script type="text/javascript" src="/path/to/js4"></script>""") + + # Check that media addition hasn't affected the original objects + self.assertEqual(str(w1.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") + + # Regression check for #12879: specifying the same CSS or JS file + # multiple times in a single Media instance should result in that file + # only being included once. + class MyWidget4(TextInput): + class Media: + css = {'all': ('/path/to/css1', '/path/to/css1')} + js = ('/path/to/js1', '/path/to/js1') + + w4 = MyWidget4() + self.assertEqual(str(w4.media), """<link href="/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script>""") + + def test_media_property(self): + ############################################################### + # Property-based media definitions + ############################################################### + + # Widget media can be defined as a property + class MyWidget4(TextInput): + def _media(self): + return Media(css={'all': ('/some/path',)}, js = ('/some/js',)) + media = property(_media) + + w4 = MyWidget4() + self.assertEqual(str(w4.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/some/js"></script>""") + + # Media properties can reference the media of their parents + class MyWidget5(MyWidget4): + def _media(self): + return super(MyWidget5, self).media + Media(css={'all': ('/other/path',)}, js = ('/other/js',)) + media = property(_media) + + w5 = MyWidget5() + self.assertEqual(str(w5.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> +<link href="/other/path" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/some/js"></script> +<script type="text/javascript" src="/other/js"></script>""") + + def test_media_property_parent_references(self): + # Media properties can reference the media of their parents, + # even if the parent media was defined using a class + class MyWidget1(TextInput): + class Media: + css = { + 'all': ('path/to/css1','/path/to/css2') + } + js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') + + class MyWidget6(MyWidget1): + def _media(self): + return super(MyWidget6, self).media + Media(css={'all': ('/other/path',)}, js = ('/other/js',)) + media = property(_media) + + w6 = MyWidget6() + self.assertEqual(str(w6.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<link href="/other/path" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> +<script type="text/javascript" src="/other/js"></script>""") + + def test_media_inheritance(self): + ############################################################### + # Inheritance of media + ############################################################### + + # If a widget extends another but provides no media definition, it inherits the parent widget's media + class MyWidget1(TextInput): + class Media: + css = { + 'all': ('path/to/css1','/path/to/css2') + } + js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') + + class MyWidget7(MyWidget1): + pass + + w7 = MyWidget7() + self.assertEqual(str(w7.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""") + + # If a widget extends another but defines media, it extends the parent widget's media by default + class MyWidget8(MyWidget1): + class Media: + css = { + 'all': ('/path/to/css3','path/to/css1') + } + js = ('/path/to/js1','/path/to/js4') + + w8 = MyWidget8() + self.assertEqual(str(w8.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> +<script type="text/javascript" src="/path/to/js4"></script>""") + + def test_media_inheritance_from_property(self): + # If a widget extends another but defines media, it extends the parents widget's media, + # even if the parent defined media using a property. + class MyWidget1(TextInput): + class Media: + css = { + 'all': ('path/to/css1','/path/to/css2') + } + js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') + + class MyWidget4(TextInput): + def _media(self): + return Media(css={'all': ('/some/path',)}, js = ('/some/js',)) + media = property(_media) + + class MyWidget9(MyWidget4): + class Media: + css = { + 'all': ('/other/path',) + } + js = ('/other/js',) + + w9 = MyWidget9() + self.assertEqual(str(w9.media), """<link href="/some/path" type="text/css" media="all" rel="stylesheet" /> +<link href="/other/path" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/some/js"></script> +<script type="text/javascript" src="/other/js"></script>""") + + # A widget can disable media inheritance by specifying 'extend=False' + class MyWidget10(MyWidget1): + class Media: + extend = False + css = { + 'all': ('/path/to/css3','path/to/css1') + } + js = ('/path/to/js1','/path/to/js4') + + w10 = MyWidget10() + self.assertEqual(str(w10.media), """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> +<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="/path/to/js4"></script>""") + + def test_media_inheritance_extends(self): + # A widget can explicitly enable full media inheritance by specifying 'extend=True' + class MyWidget1(TextInput): + class Media: + css = { + 'all': ('path/to/css1','/path/to/css2') + } + js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') + + class MyWidget11(MyWidget1): + class Media: + extend = True + css = { + 'all': ('/path/to/css3','path/to/css1') + } + js = ('/path/to/js1','/path/to/js4') + + w11 = MyWidget11() + self.assertEqual(str(w11.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> +<script type="text/javascript" src="/path/to/js4"></script>""") + + def test_media_inheritance_single_type(self): + # A widget can enable inheritance of one media type by specifying extend as a tuple + class MyWidget1(TextInput): + class Media: + css = { + 'all': ('path/to/css1','/path/to/css2') + } + js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') + + class MyWidget12(MyWidget1): + class Media: + extend = ('css',) + css = { + 'all': ('/path/to/css3','path/to/css1') + } + js = ('/path/to/js1','/path/to/js4') + + w12 = MyWidget12() + self.assertEqual(str(w12.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="/path/to/js4"></script>""") + + def test_multi_media(self): + ############################################################### + # Multi-media handling for CSS + ############################################################### + + # A widget can define CSS media for multiple output media types + class MultimediaWidget(TextInput): + class Media: + css = { + 'screen, print': ('/file1','/file2'), + 'screen': ('/file3',), + 'print': ('/file4',) + } + js = ('/path/to/js1','/path/to/js4') + + multimedia = MultimediaWidget() + self.assertEqual(str(multimedia.media), """<link href="/file4" type="text/css" media="print" rel="stylesheet" /> +<link href="/file3" type="text/css" media="screen" rel="stylesheet" /> +<link href="/file1" type="text/css" media="screen, print" rel="stylesheet" /> +<link href="/file2" type="text/css" media="screen, print" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="/path/to/js4"></script>""") + + def test_multi_widget(self): + ############################################################### + # Multiwidget media handling + ############################################################### + + class MyWidget1(TextInput): + class Media: + css = { + 'all': ('path/to/css1','/path/to/css2') + } + js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') + + class MyWidget2(TextInput): + class Media: + css = { + 'all': ('/path/to/css2','/path/to/css3') + } + js = ('/path/to/js1','/path/to/js4') + + class MyWidget3(TextInput): + class Media: + css = { + 'all': ('/path/to/css3','path/to/css1') + } + js = ('/path/to/js1','/path/to/js4') + + # MultiWidgets have a default media definition that gets all the + # media from the component widgets + class MyMultiWidget(MultiWidget): + def __init__(self, attrs=None): + widgets = [MyWidget1, MyWidget2, MyWidget3] + super(MyMultiWidget, self).__init__(widgets, attrs) + + mymulti = MyMultiWidget() + self.assertEqual(str(mymulti.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> +<script type="text/javascript" src="/path/to/js4"></script>""") + + def test_form_media(self): + ############################################################### + # Media processing for forms + ############################################################### + + class MyWidget1(TextInput): + class Media: + css = { + 'all': ('path/to/css1','/path/to/css2') + } + js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') + + class MyWidget2(TextInput): + class Media: + css = { + 'all': ('/path/to/css2','/path/to/css3') + } + js = ('/path/to/js1','/path/to/js4') + + class MyWidget3(TextInput): + class Media: + css = { + 'all': ('/path/to/css3','path/to/css1') + } + js = ('/path/to/js1','/path/to/js4') + + # You can ask a form for the media required by its widgets. + class MyForm(Form): + field1 = CharField(max_length=20, widget=MyWidget1()) + field2 = CharField(max_length=20, widget=MyWidget2()) + f1 = MyForm() + self.assertEqual(str(f1.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> +<script type="text/javascript" src="/path/to/js4"></script>""") + + # Form media can be combined to produce a single media definition. + class AnotherForm(Form): + field3 = CharField(max_length=20, widget=MyWidget3()) + f2 = AnotherForm() + self.assertEqual(str(f1.media + f2.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> +<script type="text/javascript" src="/path/to/js4"></script>""") + + # Forms can also define media, following the same rules as widgets. + class FormWithMedia(Form): + field1 = CharField(max_length=20, widget=MyWidget1()) + field2 = CharField(max_length=20, widget=MyWidget2()) + class Media: + js = ('/some/form/javascript',) + css = { + 'all': ('/some/form/css',) + } + f3 = FormWithMedia() + self.assertEqual(str(f3.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> +<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" /> +<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> +<script type="text/javascript" src="/path/to/js4"></script> +<script type="text/javascript" src="/some/form/javascript"></script>""") + + # Media works in templates + from django.template import Template, Context + self.assertEqual(Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), """<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="http://media.other.com/path/to/js2"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> +<script type="text/javascript" src="/path/to/js4"></script> +<script type="text/javascript" src="/some/form/javascript"></script><link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> +<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> +<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />""") diff --git a/tests/regressiontests/forms/tests/models.py b/tests/regressiontests/forms/tests/models.py new file mode 100644 index 0000000000..cfdd4f4bfc --- /dev/null +++ b/tests/regressiontests/forms/tests/models.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- +import datetime +from django.core.files.uploadedfile import SimpleUploadedFile +from django.forms import Form, ModelForm, FileField, ModelChoiceField +from django.test import TestCase +from regressiontests.forms.models import ChoiceModel, ChoiceOptionModel, ChoiceFieldModel, FileModel, Group, BoundaryModel, Defaults + + +class ChoiceFieldForm(ModelForm): + class Meta: + model = ChoiceFieldModel + + +class FileForm(Form): + file1 = FileField() + + +class TestTicket12510(TestCase): + ''' It is not necessary to generate choices for ModelChoiceField (regression test for #12510). ''' + def setUp(self): + self.groups = [Group.objects.create(name=name) for name in 'abc'] + + def test_choices_not_fetched_when_not_rendering(self): + def test(): + field = ModelChoiceField(Group.objects.order_by('-name')) + self.assertEqual('a', field.clean(self.groups[0].pk).name) + # only one query is required to pull the model from DB + self.assertNumQueries(1, test) + +class ModelFormCallableModelDefault(TestCase): + def test_no_empty_option(self): + "If a model's ForeignKey has blank=False and a default, no empty option is created (Refs #10792)." + option = ChoiceOptionModel.objects.create(name='default') + + choices = list(ChoiceFieldForm().fields['choice'].choices) + self.assertEquals(len(choices), 1) + self.assertEquals(choices[0], (option.pk, unicode(option))) + + def test_callable_initial_value(self): + "The initial value for a callable default returning a queryset is the pk (refs #13769)" + obj1 = ChoiceOptionModel.objects.create(id=1, name='default') + obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2') + obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3') + self.assertEquals(ChoiceFieldForm().as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice"> +<option value="1" selected="selected">ChoiceOption 1</option> +<option value="2">ChoiceOption 2</option> +<option value="3">ChoiceOption 3</option> +</select><input type="hidden" name="initial-choice" value="1" id="initial-id_choice" /></p> +<p><label for="id_choice_int">Choice int:</label> <select name="choice_int" id="id_choice_int"> +<option value="1" selected="selected">ChoiceOption 1</option> +<option value="2">ChoiceOption 2</option> +<option value="3">ChoiceOption 3</option> +</select><input type="hidden" name="initial-choice_int" value="1" id="initial-id_choice_int" /></p> +<p><label for="id_multi_choice">Multi choice:</label> <select multiple="multiple" name="multi_choice" id="id_multi_choice"> +<option value="1" selected="selected">ChoiceOption 1</option> +<option value="2">ChoiceOption 2</option> +<option value="3">ChoiceOption 3</option> +</select><input type="hidden" name="initial-multi_choice" value="1" id="initial-id_multi_choice_0" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p> +<p><label for="id_multi_choice_int">Multi choice int:</label> <select multiple="multiple" name="multi_choice_int" id="id_multi_choice_int"> +<option value="1" selected="selected">ChoiceOption 1</option> +<option value="2">ChoiceOption 2</option> +<option value="3">ChoiceOption 3</option> +</select><input type="hidden" name="initial-multi_choice_int" value="1" id="initial-id_multi_choice_int_0" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p>""") + + def test_initial_instance_value(self): + "Initial instances for model fields may also be instances (refs #7287)" + obj1 = ChoiceOptionModel.objects.create(id=1, name='default') + obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2') + obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3') + self.assertEquals(ChoiceFieldForm(initial={ + 'choice': obj2, + 'choice_int': obj2, + 'multi_choice': [obj2,obj3], + 'multi_choice_int': ChoiceOptionModel.objects.exclude(name="default"), + }).as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice"> +<option value="1">ChoiceOption 1</option> +<option value="2" selected="selected">ChoiceOption 2</option> +<option value="3">ChoiceOption 3</option> +</select><input type="hidden" name="initial-choice" value="2" id="initial-id_choice" /></p> +<p><label for="id_choice_int">Choice int:</label> <select name="choice_int" id="id_choice_int"> +<option value="1">ChoiceOption 1</option> +<option value="2" selected="selected">ChoiceOption 2</option> +<option value="3">ChoiceOption 3</option> +</select><input type="hidden" name="initial-choice_int" value="2" id="initial-id_choice_int" /></p> +<p><label for="id_multi_choice">Multi choice:</label> <select multiple="multiple" name="multi_choice" id="id_multi_choice"> +<option value="1">ChoiceOption 1</option> +<option value="2" selected="selected">ChoiceOption 2</option> +<option value="3" selected="selected">ChoiceOption 3</option> +</select><input type="hidden" name="initial-multi_choice" value="2" id="initial-id_multi_choice_0" /> +<input type="hidden" name="initial-multi_choice" value="3" id="initial-id_multi_choice_1" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p> +<p><label for="id_multi_choice_int">Multi choice int:</label> <select multiple="multiple" name="multi_choice_int" id="id_multi_choice_int"> +<option value="1">ChoiceOption 1</option> +<option value="2" selected="selected">ChoiceOption 2</option> +<option value="3" selected="selected">ChoiceOption 3</option> +</select><input type="hidden" name="initial-multi_choice_int" value="2" id="initial-id_multi_choice_int_0" /> +<input type="hidden" name="initial-multi_choice_int" value="3" id="initial-id_multi_choice_int_1" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p>""") + + + +class FormsModelTestCase(TestCase): + def test_unicode_filename(self): + # FileModel with unicode filename and data ######################### + f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')}, auto_id=False) + self.assertTrue(f.is_valid()) + self.assertTrue('file1' in f.cleaned_data) + m = FileModel.objects.create(file=f.cleaned_data['file1']) + self.assertEqual(m.file.name, u'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt') + m.delete() + + def test_boundary_conditions(self): + # Boundary conditions on a PostitiveIntegerField ######################### + class BoundaryForm(ModelForm): + class Meta: + model = BoundaryModel + + f = BoundaryForm({'positive_integer': 100}) + self.assertTrue(f.is_valid()) + f = BoundaryForm({'positive_integer': 0}) + self.assertTrue(f.is_valid()) + f = BoundaryForm({'positive_integer': -100}) + self.assertFalse(f.is_valid()) + + def test_formfield_initial(self): + # Formfield initial values ######## + # If the model has default values for some fields, they are used as the formfield + # initial values. + class DefaultsForm(ModelForm): + class Meta: + model = Defaults + + self.assertEqual(DefaultsForm().fields['name'].initial, u'class default value') + self.assertEqual(DefaultsForm().fields['def_date'].initial, datetime.date(1980, 1, 1)) + self.assertEqual(DefaultsForm().fields['value'].initial, 42) + r1 = DefaultsForm()['callable_default'].as_widget() + r2 = DefaultsForm()['callable_default'].as_widget() + self.assertNotEqual(r1, r2) + + # In a ModelForm that is passed an instance, the initial values come from the + # instance's values, not the model's defaults. + foo_instance = Defaults(name=u'instance value', def_date=datetime.date(1969, 4, 4), value=12) + instance_form = DefaultsForm(instance=foo_instance) + self.assertEqual(instance_form.initial['name'], u'instance value') + self.assertEqual(instance_form.initial['def_date'], datetime.date(1969, 4, 4)) + self.assertEqual(instance_form.initial['value'], 12) + + from django.forms import CharField + + class ExcludingForm(ModelForm): + name = CharField(max_length=255) + + class Meta: + model = Defaults + exclude = ['name', 'callable_default'] + + f = ExcludingForm({'name': u'Hello', 'value': 99, 'def_date': datetime.date(1999, 3, 2)}) + self.assertTrue(f.is_valid()) + self.assertEqual(f.cleaned_data['name'], u'Hello') + obj = f.save() + self.assertEqual(obj.name, u'class default value') + self.assertEqual(obj.value, 99) + self.assertEqual(obj.def_date, datetime.date(1999, 3, 2)) diff --git a/tests/regressiontests/forms/tests/regressions.py b/tests/regressiontests/forms/tests/regressions.py new file mode 100644 index 0000000000..3f69e0aa6e --- /dev/null +++ b/tests/regressiontests/forms/tests/regressions.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +from django.forms import * +from django.utils.unittest import TestCase +from django.utils.translation import ugettext_lazy, activate, deactivate + +class FormsRegressionsTestCase(TestCase): + def test_class(self): + # Tests to prevent against recurrences of earlier bugs. + extra_attrs = {'class': 'special'} + + class TestForm(Form): + f1 = CharField(max_length=10, widget=TextInput(attrs=extra_attrs)) + f2 = CharField(widget=TextInput(attrs=extra_attrs)) + + self.assertEqual(TestForm(auto_id=False).as_p(), u'<p>F1: <input type="text" class="special" name="f1" maxlength="10" /></p>\n<p>F2: <input type="text" class="special" name="f2" /></p>') + + def test_regression_3600(self): + # Tests for form i18n # + # There were some problems with form translations in #3600 + + class SomeForm(Form): + username = CharField(max_length=10, label=ugettext_lazy('Username')) + + f = SomeForm() + self.assertEqual(f.as_p(), '<p><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>') + + # Translations are done at rendering time, so multi-lingual apps can define forms) + activate('de') + self.assertEqual(f.as_p(), '<p><label for="id_username">Benutzername:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>') + activate('pl') + self.assertEqual(f.as_p(), u'<p><label for="id_username">Nazwa u\u017cytkownika:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>') + deactivate() + + def test_regression_5216(self): + # There was some problems with form translations in #5216 + class SomeForm(Form): + field_1 = CharField(max_length=10, label=ugettext_lazy('field_1')) + field_2 = CharField(max_length=10, label=ugettext_lazy('field_2'), widget=TextInput(attrs={'id': 'field_2_id'})) + + f = SomeForm() + self.assertEqual(f['field_1'].label_tag(), '<label for="id_field_1">field_1</label>') + self.assertEqual(f['field_2'].label_tag(), '<label for="field_2_id">field_2</label>') + + # Unicode decoding problems... + GENDERS = ((u'\xc5', u'En tied\xe4'), (u'\xf8', u'Mies'), (u'\xdf', u'Nainen')) + + class SomeForm(Form): + somechoice = ChoiceField(choices=GENDERS, widget=RadioSelect(), label=u'\xc5\xf8\xdf') + + f = SomeForm() + self.assertEqual(f.as_p(), u'<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>') + + # Testing choice validation with UTF-8 bytestrings as input (these are the + # Russian abbreviations "мес." and "шт.". + UNITS = (('\xd0\xbc\xd0\xb5\xd1\x81.', '\xd0\xbc\xd0\xb5\xd1\x81.'), ('\xd1\x88\xd1\x82.', '\xd1\x88\xd1\x82.')) + f = ChoiceField(choices=UNITS) + self.assertEqual(f.clean(u'\u0448\u0442.'), u'\u0448\u0442.') + self.assertEqual(f.clean('\xd1\x88\xd1\x82.'), u'\u0448\u0442.') + + # Translated error messages used to be buggy. + activate('ru') + f = SomeForm({}) + self.assertEqual(f.as_p(), u'<ul class="errorlist"><li>\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n<p><label for="id_somechoice_0">\xc5\xf8\xdf:</label> <ul>\n<li><label for="id_somechoice_0"><input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" /> En tied\xe4</label></li>\n<li><label for="id_somechoice_1"><input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" /> Mies</label></li>\n<li><label for="id_somechoice_2"><input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" /> Nainen</label></li>\n</ul></p>') + deactivate() + + # Deep copying translated text shouldn't raise an error) + from django.utils.translation import gettext_lazy + + class CopyForm(Form): + degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),))) + + f = CopyForm() + + def test_misc(self): + # There once was a problem with Form fields called "data". Let's make sure that + # doesn't come back. + class DataForm(Form): + data = CharField(max_length=10) + + f = DataForm({'data': 'xyzzy'}) + self.assertTrue(f.is_valid()) + self.assertEqual(f.cleaned_data, {'data': u'xyzzy'}) + + # A form with *only* hidden fields that has errors is going to be very unusual. + class HiddenForm(Form): + data = IntegerField(widget=HiddenInput) + + f = HiddenForm({}) + self.assertEqual(f.as_p(), u'<ul class="errorlist"><li>(Hidden field data) This field is required.</li></ul>\n<p> <input type="hidden" name="data" id="id_data" /></p>') + self.assertEqual(f.as_table(), u'<tr><td colspan="2"><ul class="errorlist"><li>(Hidden field data) This field is required.</li></ul><input type="hidden" name="data" id="id_data" /></td></tr>') + + def test_xss_error_messages(self): + ################################################### + # Tests for XSS vulnerabilities in error messages # + ################################################### + + # The forms layer doesn't escape input values directly because error messages + # might be presented in non-HTML contexts. Instead, the message is just marked + # for escaping by the template engine. So we'll need to construct a little + # silly template to trigger the escaping. + from django.template import Template, Context + t = Template('{{ form.errors }}') + + class SomeForm(Form): + field = ChoiceField(choices=[('one', 'One')]) + + f = SomeForm({'field': '<script>'}) + self.assertEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. <script> is not one of the available choices.</li></ul></li></ul>') + + class SomeForm(Form): + field = MultipleChoiceField(choices=[('one', 'One')]) + + f = SomeForm({'field': ['<script>']}) + self.assertEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. <script> is not one of the available choices.</li></ul></li></ul>') + + from regressiontests.forms.models import ChoiceModel + + class SomeForm(Form): + field = ModelMultipleChoiceField(ChoiceModel.objects.all()) + + f = SomeForm({'field': ['<script>']}) + self.assertEqual(t.render(Context({'form': f})), u'<ul class="errorlist"><li>field<ul class="errorlist"><li>"<script>" is not a valid value for a primary key.</li></ul></li></ul>') diff --git a/tests/regressiontests/forms/tests/util.py b/tests/regressiontests/forms/tests/util.py new file mode 100644 index 0000000000..81fec1cf91 --- /dev/null +++ b/tests/regressiontests/forms/tests/util.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +from django.core.exceptions import ValidationError +from django.forms.util import * +from django.utils.translation import ugettext_lazy +from django.utils.unittest import TestCase + + +class FormsUtilTestCase(TestCase): + # Tests for forms/util.py module. + + def test_flatatt(self): + ########### + # flatatt # + ########### + + self.assertEqual(flatatt({'id': "header"}), u' id="header"') + self.assertEqual(flatatt({'class': "news", 'title': "Read this"}), u' class="news" title="Read this"') + self.assertEqual(flatatt({}), u'') + + def test_validation_error(self): + ################### + # ValidationError # + ################### + + # Can take a string. + self.assertEqual(str(ErrorList(ValidationError("There was an error.").messages)), + '<ul class="errorlist"><li>There was an error.</li></ul>') + + # Can take a unicode string. + self.assertEqual(str(ErrorList(ValidationError(u"Not \u03C0.").messages)), + '<ul class="errorlist"><li>Not π.</li></ul>') + + # Can take a lazy string. + self.assertEqual(str(ErrorList(ValidationError(ugettext_lazy("Error.")).messages)), + '<ul class="errorlist"><li>Error.</li></ul>') + + # Can take a list. + self.assertEqual(str(ErrorList(ValidationError(["Error one.", "Error two."]).messages)), + '<ul class="errorlist"><li>Error one.</li><li>Error two.</li></ul>') + + # Can take a mixture in a list. + self.assertEqual(str(ErrorList(ValidationError(["First error.", u"Not \u03C0.", ugettext_lazy("Error.")]).messages)), + '<ul class="errorlist"><li>First error.</li><li>Not π.</li><li>Error.</li></ul>') + + class VeryBadError: + def __unicode__(self): return u"A very bad error." + + # Can take a non-string. + self.assertEqual(str(ErrorList(ValidationError(VeryBadError()).messages)), + '<ul class="errorlist"><li>A very bad error.</li></ul>') + + # Escapes non-safe input but not input marked safe. + example = 'Example of link: <a href="http://www.example.com/">example</a>' + self.assertEqual(str(ErrorList([example])), + '<ul class="errorlist"><li>Example of link: <a href="http://www.example.com/">example</a></li></ul>') + self.assertEqual(str(ErrorList([mark_safe(example)])), + '<ul class="errorlist"><li>Example of link: <a href="http://www.example.com/">example</a></li></ul>') diff --git a/tests/regressiontests/forms/validators.py b/tests/regressiontests/forms/tests/validators.py similarity index 100% rename from tests/regressiontests/forms/validators.py rename to tests/regressiontests/forms/tests/validators.py diff --git a/tests/regressiontests/forms/tests/widgets.py b/tests/regressiontests/forms/tests/widgets.py new file mode 100644 index 0000000000..e21895b121 --- /dev/null +++ b/tests/regressiontests/forms/tests/widgets.py @@ -0,0 +1,1135 @@ +# -*- coding: utf-8 -*- +import datetime +from decimal import Decimal +import re +import time +from django.conf import settings +from django.core.files.uploadedfile import SimpleUploadedFile +from django.forms import * +from django.forms.widgets import RadioFieldRenderer +from django.utils import copycompat as copy +from django.utils import formats +from django.utils.safestring import mark_safe +from django.utils.translation import activate, deactivate +from django.utils.unittest import TestCase + + + +class FormsWidgetTestCase(TestCase): + # Each Widget class corresponds to an HTML form widget. A Widget knows how to + # render itself, given a field name and some data. Widgets don't perform + # validation. + def test_textinput(self): + w = TextInput() + self.assertEqual(w.render('email', ''), u'<input type="text" name="email" />') + self.assertEqual(w.render('email', None), u'<input type="text" name="email" />') + self.assertEqual(w.render('email', 'test@example.com'), u'<input type="text" name="email" value="test@example.com" />') + self.assertEqual(w.render('email', 'some "quoted" & ampersanded value'), u'<input type="text" name="email" value="some "quoted" & ampersanded value" />') + self.assertEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), u'<input type="text" name="email" value="test@example.com" class="fun" />') + + # Note that doctest in Python 2.4 (and maybe 2.5?) doesn't support non-ascii + # characters in output, so we're displaying the repr() here. + self.assertEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<input type="text" name="email" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" class="fun" />') + + # You can also pass 'attrs' to the constructor: + w = TextInput(attrs={'class': 'fun'}) + self.assertEqual(w.render('email', ''), u'<input type="text" class="fun" name="email" />') + self.assertEqual(w.render('email', 'foo@example.com'), u'<input type="text" class="fun" value="foo@example.com" name="email" />') + + # 'attrs' passed to render() get precedence over those passed to the constructor: + w = TextInput(attrs={'class': 'pretty'}) + self.assertEqual(w.render('email', '', attrs={'class': 'special'}), u'<input type="text" class="special" name="email" />') + + # 'attrs' can be safe-strings if needed) + w = TextInput(attrs={'onBlur': mark_safe("function('foo')")}) + self.assertEqual(w.render('email', ''), u'<input onBlur="function(\'foo\')" type="text" name="email" />') + + def test_passwordinput(self): + w = PasswordInput() + self.assertEqual(w.render('email', ''), u'<input type="password" name="email" />') + self.assertEqual(w.render('email', None), u'<input type="password" name="email" />') + self.assertEqual(w.render('email', 'secret'), u'<input type="password" name="email" />') + + # The render_value argument lets you specify whether the widget should render + # its value. For security reasons, this is off by default. + w = PasswordInput(render_value=True) + self.assertEqual(w.render('email', ''), u'<input type="password" name="email" />') + self.assertEqual(w.render('email', None), u'<input type="password" name="email" />') + self.assertEqual(w.render('email', 'test@example.com'), u'<input type="password" name="email" value="test@example.com" />') + self.assertEqual(w.render('email', 'some "quoted" & ampersanded value'), u'<input type="password" name="email" value="some "quoted" & ampersanded value" />') + self.assertEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), u'<input type="password" name="email" value="test@example.com" class="fun" />') + + # You can also pass 'attrs' to the constructor: + w = PasswordInput(attrs={'class': 'fun'}, render_value=True) + self.assertEqual(w.render('email', ''), u'<input type="password" class="fun" name="email" />') + self.assertEqual(w.render('email', 'foo@example.com'), u'<input type="password" class="fun" value="foo@example.com" name="email" />') + + # 'attrs' passed to render() get precedence over those passed to the constructor: + w = PasswordInput(attrs={'class': 'pretty'}, render_value=True) + self.assertEqual(w.render('email', '', attrs={'class': 'special'}), u'<input type="password" class="special" name="email" />') + + self.assertEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<input type="password" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />') + + def test_hiddeninput(self): + w = HiddenInput() + self.assertEqual(w.render('email', ''), u'<input type="hidden" name="email" />') + self.assertEqual(w.render('email', None), u'<input type="hidden" name="email" />') + self.assertEqual(w.render('email', 'test@example.com'), u'<input type="hidden" name="email" value="test@example.com" />') + self.assertEqual(w.render('email', 'some "quoted" & ampersanded value'), u'<input type="hidden" name="email" value="some "quoted" & ampersanded value" />') + self.assertEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), u'<input type="hidden" name="email" value="test@example.com" class="fun" />') + + # You can also pass 'attrs' to the constructor: + w = HiddenInput(attrs={'class': 'fun'}) + self.assertEqual(w.render('email', ''), u'<input type="hidden" class="fun" name="email" />') + self.assertEqual(w.render('email', 'foo@example.com'), u'<input type="hidden" class="fun" value="foo@example.com" name="email" />') + + # 'attrs' passed to render() get precedence over those passed to the constructor: + w = HiddenInput(attrs={'class': 'pretty'}) + self.assertEqual(w.render('email', '', attrs={'class': 'special'}), u'<input type="hidden" class="special" name="email" />') + + self.assertEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<input type="hidden" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />') + + # 'attrs' passed to render() get precedence over those passed to the constructor: + w = HiddenInput(attrs={'class': 'pretty'}) + self.assertEqual(w.render('email', '', attrs={'class': 'special'}), u'<input type="hidden" class="special" name="email" />') + + # Boolean values are rendered to their string forms ("True" and "False"). + w = HiddenInput() + self.assertEqual(w.render('get_spam', False), u'<input type="hidden" name="get_spam" value="False" />') + self.assertEqual(w.render('get_spam', True), u'<input type="hidden" name="get_spam" value="True" />') + + def test_multiplehiddeninput(self): + w = MultipleHiddenInput() + self.assertEqual(w.render('email', []), u'') + self.assertEqual(w.render('email', None), u'') + self.assertEqual(w.render('email', ['test@example.com']), u'<input type="hidden" name="email" value="test@example.com" />') + self.assertEqual(w.render('email', ['some "quoted" & ampersanded value']), u'<input type="hidden" name="email" value="some "quoted" & ampersanded value" />') + self.assertEqual(w.render('email', ['test@example.com', 'foo@example.com']), u'<input type="hidden" name="email" value="test@example.com" />\n<input type="hidden" name="email" value="foo@example.com" />') + self.assertEqual(w.render('email', ['test@example.com'], attrs={'class': 'fun'}), u'<input type="hidden" name="email" value="test@example.com" class="fun" />') + self.assertEqual(w.render('email', ['test@example.com', 'foo@example.com'], attrs={'class': 'fun'}), u'<input type="hidden" name="email" value="test@example.com" class="fun" />\n<input type="hidden" name="email" value="foo@example.com" class="fun" />') + + # You can also pass 'attrs' to the constructor: + w = MultipleHiddenInput(attrs={'class': 'fun'}) + self.assertEqual(w.render('email', []), u'') + self.assertEqual(w.render('email', ['foo@example.com']), u'<input type="hidden" class="fun" value="foo@example.com" name="email" />') + self.assertEqual(w.render('email', ['foo@example.com', 'test@example.com']), u'<input type="hidden" class="fun" value="foo@example.com" name="email" />\n<input type="hidden" class="fun" value="test@example.com" name="email" />') + + # 'attrs' passed to render() get precedence over those passed to the constructor: + w = MultipleHiddenInput(attrs={'class': 'pretty'}) + self.assertEqual(w.render('email', ['foo@example.com'], attrs={'class': 'special'}), u'<input type="hidden" class="special" value="foo@example.com" name="email" />') + + self.assertEqual(w.render('email', ['ŠĐĆŽćžšđ'], attrs={'class': 'fun'}), u'<input type="hidden" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />') + + # 'attrs' passed to render() get precedence over those passed to the constructor: + w = MultipleHiddenInput(attrs={'class': 'pretty'}) + self.assertEqual(w.render('email', ['foo@example.com'], attrs={'class': 'special'}), u'<input type="hidden" class="special" value="foo@example.com" name="email" />') + + # Each input gets a separate ID. + w = MultipleHiddenInput() + self.assertEqual(w.render('letters', list('abc'), attrs={'id': 'hideme'}), u'<input type="hidden" name="letters" value="a" id="hideme_0" />\n<input type="hidden" name="letters" value="b" id="hideme_1" />\n<input type="hidden" name="letters" value="c" id="hideme_2" />') + + def test_fileinput(self): + # FileInput widgets don't ever show the value, because the old value is of no use + # if you are updating the form or if the provided file generated an error. + w = FileInput() + self.assertEqual(w.render('email', ''), u'<input type="file" name="email" />') + self.assertEqual(w.render('email', None), u'<input type="file" name="email" />') + self.assertEqual(w.render('email', 'test@example.com'), u'<input type="file" name="email" />') + self.assertEqual(w.render('email', 'some "quoted" & ampersanded value'), u'<input type="file" name="email" />') + self.assertEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), u'<input type="file" name="email" class="fun" />') + + # You can also pass 'attrs' to the constructor: + w = FileInput(attrs={'class': 'fun'}) + self.assertEqual(w.render('email', ''), u'<input type="file" class="fun" name="email" />') + self.assertEqual(w.render('email', 'foo@example.com'), u'<input type="file" class="fun" name="email" />') + + self.assertEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<input type="file" class="fun" name="email" />') + + # Test for the behavior of _has_changed for FileInput. The value of data will + # more than likely come from request.FILES. The value of initial data will + # likely be a filename stored in the database. Since its value is of no use to + # a FileInput it is ignored. + w = FileInput() + + # No file was uploaded and no initial data. + self.assertFalse(w._has_changed(u'', None)) + + # A file was uploaded and no initial data. + self.assertTrue(w._has_changed(u'', {'filename': 'resume.txt', 'content': 'My resume'})) + + # A file was not uploaded, but there is initial data + self.assertFalse(w._has_changed(u'resume.txt', None)) + + # A file was uploaded and there is initial data (file identity is not dealt + # with here) + self.assertTrue(w._has_changed('resume.txt', {'filename': 'resume.txt', 'content': 'My resume'})) + + def test_textarea(self): + w = Textarea() + self.assertEqual(w.render('msg', ''), u'<textarea rows="10" cols="40" name="msg"></textarea>') + self.assertEqual(w.render('msg', None), u'<textarea rows="10" cols="40" name="msg"></textarea>') + self.assertEqual(w.render('msg', 'value'), u'<textarea rows="10" cols="40" name="msg">value</textarea>') + self.assertEqual(w.render('msg', 'some "quoted" & ampersanded value'), u'<textarea rows="10" cols="40" name="msg">some "quoted" & ampersanded value</textarea>') + self.assertEqual(w.render('msg', mark_safe('pre "quoted" value')), u'<textarea rows="10" cols="40" name="msg">pre "quoted" value</textarea>') + self.assertEqual(w.render('msg', 'value', attrs={'class': 'pretty', 'rows': 20}), u'<textarea class="pretty" rows="20" cols="40" name="msg">value</textarea>') + + # You can also pass 'attrs' to the constructor: + w = Textarea(attrs={'class': 'pretty'}) + self.assertEqual(w.render('msg', ''), u'<textarea rows="10" cols="40" name="msg" class="pretty"></textarea>') + self.assertEqual(w.render('msg', 'example'), u'<textarea rows="10" cols="40" name="msg" class="pretty">example</textarea>') + + # 'attrs' passed to render() get precedence over those passed to the constructor: + w = Textarea(attrs={'class': 'pretty'}) + self.assertEqual(w.render('msg', '', attrs={'class': 'special'}), u'<textarea rows="10" cols="40" name="msg" class="special"></textarea>') + + self.assertEqual(w.render('msg', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), u'<textarea rows="10" cols="40" name="msg" class="fun">\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111</textarea>') + + def test_checkboxinput(self): + w = CheckboxInput() + self.assertEqual(w.render('is_cool', ''), u'<input type="checkbox" name="is_cool" />') + self.assertEqual(w.render('is_cool', None), u'<input type="checkbox" name="is_cool" />') + self.assertEqual(w.render('is_cool', False), u'<input type="checkbox" name="is_cool" />') + self.assertEqual(w.render('is_cool', True), u'<input checked="checked" type="checkbox" name="is_cool" />') + + # Using any value that's not in ('', None, False, True) will check the checkbox + # and set the 'value' attribute. + self.assertEqual(w.render('is_cool', 'foo'), u'<input checked="checked" type="checkbox" name="is_cool" value="foo" />') + + self.assertEqual(w.render('is_cool', False, attrs={'class': 'pretty'}), u'<input type="checkbox" name="is_cool" class="pretty" />') + + # You can also pass 'attrs' to the constructor: + w = CheckboxInput(attrs={'class': 'pretty'}) + self.assertEqual(w.render('is_cool', ''), u'<input type="checkbox" class="pretty" name="is_cool" />') + + # 'attrs' passed to render() get precedence over those passed to the constructor: + w = CheckboxInput(attrs={'class': 'pretty'}) + self.assertEqual(w.render('is_cool', '', attrs={'class': 'special'}), u'<input type="checkbox" class="special" name="is_cool" />') + + # You can pass 'check_test' to the constructor. This is a callable that takes the + # value and returns True if the box should be checked. + w = CheckboxInput(check_test=lambda value: value.startswith('hello')) + self.assertEqual(w.render('greeting', ''), u'<input type="checkbox" name="greeting" />') + self.assertEqual(w.render('greeting', 'hello'), u'<input checked="checked" type="checkbox" name="greeting" value="hello" />') + self.assertEqual(w.render('greeting', 'hello there'), u'<input checked="checked" type="checkbox" name="greeting" value="hello there" />') + self.assertEqual(w.render('greeting', 'hello & goodbye'), u'<input checked="checked" type="checkbox" name="greeting" value="hello & goodbye" />') + + # A subtlety: If the 'check_test' argument cannot handle a value and raises any + # exception during its __call__, then the exception will be swallowed and the box + # will not be checked. In this example, the 'check_test' assumes the value has a + # startswith() method, which fails for the values True, False and None. + self.assertEqual(w.render('greeting', True), u'<input type="checkbox" name="greeting" />') + self.assertEqual(w.render('greeting', False), u'<input type="checkbox" name="greeting" />') + self.assertEqual(w.render('greeting', None), u'<input type="checkbox" name="greeting" />') + + # The CheckboxInput widget will return False if the key is not found in the data + # dictionary (because HTML form submission doesn't send any result for unchecked + # checkboxes). + self.assertFalse(w.value_from_datadict({}, {}, 'testing')) + + self.assertFalse(w._has_changed(None, None)) + self.assertFalse(w._has_changed(None, u'')) + self.assertFalse(w._has_changed(u'', None)) + self.assertFalse(w._has_changed(u'', u'')) + self.assertTrue(w._has_changed(False, u'on')) + self.assertFalse(w._has_changed(True, u'on')) + self.assertTrue(w._has_changed(True, u'')) + + def test_select(self): + w = Select() + self.assertEqual(w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select name="beatle"> +<option value="J" selected="selected">John</option> +<option value="P">Paul</option> +<option value="G">George</option> +<option value="R">Ringo</option> +</select>""") + + # If the value is None, none of the options are selected: + self.assertEqual(w.render('beatle', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select name="beatle"> +<option value="J">John</option> +<option value="P">Paul</option> +<option value="G">George</option> +<option value="R">Ringo</option> +</select>""") + + # If the value corresponds to a label (but not to an option value), none of the options are selected: + self.assertEqual(w.render('beatle', 'John', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select name="beatle"> +<option value="J">John</option> +<option value="P">Paul</option> +<option value="G">George</option> +<option value="R">Ringo</option> +</select>""") + + # The value is compared to its str(): + self.assertEqual(w.render('num', 2, choices=[('1', '1'), ('2', '2'), ('3', '3')]), """<select name="num"> +<option value="1">1</option> +<option value="2" selected="selected">2</option> +<option value="3">3</option> +</select>""") + self.assertEqual(w.render('num', '2', choices=[(1, 1), (2, 2), (3, 3)]), """<select name="num"> +<option value="1">1</option> +<option value="2" selected="selected">2</option> +<option value="3">3</option> +</select>""") + self.assertEqual(w.render('num', 2, choices=[(1, 1), (2, 2), (3, 3)]), """<select name="num"> +<option value="1">1</option> +<option value="2" selected="selected">2</option> +<option value="3">3</option> +</select>""") + + # The 'choices' argument can be any iterable: + from itertools import chain + def get_choices(): + for i in range(5): + yield (i, i) + self.assertEqual(w.render('num', 2, choices=get_choices()), """<select name="num"> +<option value="0">0</option> +<option value="1">1</option> +<option value="2" selected="selected">2</option> +<option value="3">3</option> +<option value="4">4</option> +</select>""") + things = ({'id': 1, 'name': 'And Boom'}, {'id': 2, 'name': 'One More Thing!'}) + class SomeForm(Form): + somechoice = ChoiceField(choices=chain((('', '-'*9),), [(thing['id'], thing['name']) for thing in things])) + f = SomeForm() + self.assertEqual(f.as_table(), u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>') + self.assertEqual(f.as_table(), u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>') + f = SomeForm({'somechoice': 2}) + self.assertEqual(f.as_table(), u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="">---------</option>\n<option value="1">And Boom</option>\n<option value="2" selected="selected">One More Thing!</option>\n</select></td></tr>') + + # You can also pass 'choices' to the constructor: + w = Select(choices=[(1, 1), (2, 2), (3, 3)]) + self.assertEqual(w.render('num', 2), """<select name="num"> +<option value="1">1</option> +<option value="2" selected="selected">2</option> +<option value="3">3</option> +</select>""") + + # If 'choices' is passed to both the constructor and render(), then they'll both be in the output: + self.assertEqual(w.render('num', 2, choices=[(4, 4), (5, 5)]), """<select name="num"> +<option value="1">1</option> +<option value="2" selected="selected">2</option> +<option value="3">3</option> +<option value="4">4</option> +<option value="5">5</option> +</select>""") + + # Choices are escaped correctly + self.assertEqual(w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you > me')))), """<select name="escape"> +<option value="1">1</option> +<option value="2">2</option> +<option value="3">3</option> +<option value="bad">you & me</option> +<option value="good">you > me</option> +</select>""") + + # Unicode choices are correctly rendered as HTML + self.assertEqual(w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), u'<select name="email">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected="selected">\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</option>\n<option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>\n</select>') + + # If choices is passed to the constructor and is a generator, it can be iterated + # over multiple times without getting consumed: + w = Select(choices=get_choices()) + self.assertEqual(w.render('num', 2), """<select name="num"> +<option value="0">0</option> +<option value="1">1</option> +<option value="2" selected="selected">2</option> +<option value="3">3</option> +<option value="4">4</option> +</select>""") + self.assertEqual(w.render('num', 3), """<select name="num"> +<option value="0">0</option> +<option value="1">1</option> +<option value="2">2</option> +<option value="3" selected="selected">3</option> +<option value="4">4</option> +</select>""") + + # Choices can be nested one level in order to create HTML optgroups: + w.choices=(('outer1', 'Outer 1'), ('Group "1"', (('inner1', 'Inner 1'), ('inner2', 'Inner 2')))) + self.assertEqual(w.render('nestchoice', None), """<select name="nestchoice"> +<option value="outer1">Outer 1</option> +<optgroup label="Group "1""> +<option value="inner1">Inner 1</option> +<option value="inner2">Inner 2</option> +</optgroup> +</select>""") + + self.assertEqual(w.render('nestchoice', 'outer1'), """<select name="nestchoice"> +<option value="outer1" selected="selected">Outer 1</option> +<optgroup label="Group "1""> +<option value="inner1">Inner 1</option> +<option value="inner2">Inner 2</option> +</optgroup> +</select>""") + + self.assertEqual(w.render('nestchoice', 'inner1'), """<select name="nestchoice"> +<option value="outer1">Outer 1</option> +<optgroup label="Group "1""> +<option value="inner1" selected="selected">Inner 1</option> +<option value="inner2">Inner 2</option> +</optgroup> +</select>""") + + def test_nullbooleanselect(self): + w = NullBooleanSelect() + self.assertTrue(w.render('is_cool', True), """<select name="is_cool"> +<option value="1">Unknown</option> +<option value="2" selected="selected">Yes</option> +<option value="3">No</option> +</select>""") + self.assertEqual(w.render('is_cool', False), """<select name="is_cool"> +<option value="1">Unknown</option> +<option value="2">Yes</option> +<option value="3" selected="selected">No</option> +</select>""") + self.assertEqual(w.render('is_cool', None), """<select name="is_cool"> +<option value="1" selected="selected">Unknown</option> +<option value="2">Yes</option> +<option value="3">No</option> +</select>""") + self.assertEqual(w.render('is_cool', '2'), """<select name="is_cool"> +<option value="1">Unknown</option> +<option value="2" selected="selected">Yes</option> +<option value="3">No</option> +</select>""") + self.assertEqual(w.render('is_cool', '3'), """<select name="is_cool"> +<option value="1">Unknown</option> +<option value="2">Yes</option> +<option value="3" selected="selected">No</option> +</select>""") + self.assertTrue(w._has_changed(False, None)) + self.assertTrue(w._has_changed(None, False)) + self.assertFalse(w._has_changed(None, None)) + self.assertFalse(w._has_changed(False, False)) + self.assertTrue(w._has_changed(True, False)) + self.assertTrue(w._has_changed(True, None)) + self.assertTrue(w._has_changed(True, False)) + + def test_selectmultiple(self): + w = SelectMultiple() + self.assertEqual(w.render('beatles', ['J'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select multiple="multiple" name="beatles"> +<option value="J" selected="selected">John</option> +<option value="P">Paul</option> +<option value="G">George</option> +<option value="R">Ringo</option> +</select>""") + self.assertEqual(w.render('beatles', ['J', 'P'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select multiple="multiple" name="beatles"> +<option value="J" selected="selected">John</option> +<option value="P" selected="selected">Paul</option> +<option value="G">George</option> +<option value="R">Ringo</option> +</select>""") + self.assertEqual(w.render('beatles', ['J', 'P', 'R'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select multiple="multiple" name="beatles"> +<option value="J" selected="selected">John</option> +<option value="P" selected="selected">Paul</option> +<option value="G">George</option> +<option value="R" selected="selected">Ringo</option> +</select>""") + + # If the value is None, none of the options are selected: + self.assertEqual(w.render('beatles', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select multiple="multiple" name="beatles"> +<option value="J">John</option> +<option value="P">Paul</option> +<option value="G">George</option> +<option value="R">Ringo</option> +</select>""") + + # If the value corresponds to a label (but not to an option value), none of the options are selected: + self.assertEqual(w.render('beatles', ['John'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select multiple="multiple" name="beatles"> +<option value="J">John</option> +<option value="P">Paul</option> +<option value="G">George</option> +<option value="R">Ringo</option> +</select>""") + + # If multiple values are given, but some of them are not valid, the valid ones are selected: + self.assertEqual(w.render('beatles', ['J', 'G', 'foo'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<select multiple="multiple" name="beatles"> +<option value="J" selected="selected">John</option> +<option value="P">Paul</option> +<option value="G" selected="selected">George</option> +<option value="R">Ringo</option> +</select>""") + + # The value is compared to its str(): + self.assertEqual(w.render('nums', [2], choices=[('1', '1'), ('2', '2'), ('3', '3')]), """<select multiple="multiple" name="nums"> +<option value="1">1</option> +<option value="2" selected="selected">2</option> +<option value="3">3</option> +</select>""") + self.assertEqual(w.render('nums', ['2'], choices=[(1, 1), (2, 2), (3, 3)]), """<select multiple="multiple" name="nums"> +<option value="1">1</option> +<option value="2" selected="selected">2</option> +<option value="3">3</option> +</select>""") + self.assertEqual(w.render('nums', [2], choices=[(1, 1), (2, 2), (3, 3)]), """<select multiple="multiple" name="nums"> +<option value="1">1</option> +<option value="2" selected="selected">2</option> +<option value="3">3</option> +</select>""") + + # The 'choices' argument can be any iterable: + def get_choices(): + for i in range(5): + yield (i, i) + self.assertEqual(w.render('nums', [2], choices=get_choices()), """<select multiple="multiple" name="nums"> +<option value="0">0</option> +<option value="1">1</option> +<option value="2" selected="selected">2</option> +<option value="3">3</option> +<option value="4">4</option> +</select>""") + + # You can also pass 'choices' to the constructor: + w = SelectMultiple(choices=[(1, 1), (2, 2), (3, 3)]) + self.assertEqual(w.render('nums', [2]), """<select multiple="multiple" name="nums"> +<option value="1">1</option> +<option value="2" selected="selected">2</option> +<option value="3">3</option> +</select>""") + + # If 'choices' is passed to both the constructor and render(), then they'll both be in the output: + self.assertEqual(w.render('nums', [2], choices=[(4, 4), (5, 5)]), """<select multiple="multiple" name="nums"> +<option value="1">1</option> +<option value="2" selected="selected">2</option> +<option value="3">3</option> +<option value="4">4</option> +<option value="5">5</option> +</select>""") + + # Choices are escaped correctly + self.assertEqual(w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you > me')))), """<select multiple="multiple" name="escape"> +<option value="1">1</option> +<option value="2">2</option> +<option value="3">3</option> +<option value="bad">you & me</option> +<option value="good">you > me</option> +</select>""") + + # Unicode choices are correctly rendered as HTML + self.assertEqual(w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), u'<select multiple="multiple" name="nums">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected="selected">\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</option>\n<option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>\n</select>') + + # Test the usage of _has_changed + self.assertFalse(w._has_changed(None, None)) + self.assertFalse(w._has_changed([], None)) + self.assertTrue(w._has_changed(None, [u'1'])) + self.assertFalse(w._has_changed([1, 2], [u'1', u'2'])) + self.assertTrue(w._has_changed([1, 2], [u'1'])) + self.assertTrue(w._has_changed([1, 2], [u'1', u'3'])) + + # Choices can be nested one level in order to create HTML optgroups: + w.choices = (('outer1', 'Outer 1'), ('Group "1"', (('inner1', 'Inner 1'), ('inner2', 'Inner 2')))) + self.assertEqual(w.render('nestchoice', None), """<select multiple="multiple" name="nestchoice"> +<option value="outer1">Outer 1</option> +<optgroup label="Group "1""> +<option value="inner1">Inner 1</option> +<option value="inner2">Inner 2</option> +</optgroup> +</select>""") + + self.assertEqual(w.render('nestchoice', ['outer1']), """<select multiple="multiple" name="nestchoice"> +<option value="outer1" selected="selected">Outer 1</option> +<optgroup label="Group "1""> +<option value="inner1">Inner 1</option> +<option value="inner2">Inner 2</option> +</optgroup> +</select>""") + + self.assertEqual(w.render('nestchoice', ['inner1']), """<select multiple="multiple" name="nestchoice"> +<option value="outer1">Outer 1</option> +<optgroup label="Group "1""> +<option value="inner1" selected="selected">Inner 1</option> +<option value="inner2">Inner 2</option> +</optgroup> +</select>""") + + self.assertEqual(w.render('nestchoice', ['outer1', 'inner2']), """<select multiple="multiple" name="nestchoice"> +<option value="outer1" selected="selected">Outer 1</option> +<optgroup label="Group "1""> +<option value="inner1">Inner 1</option> +<option value="inner2" selected="selected">Inner 2</option> +</optgroup> +</select>""") + + def test_radioselect(self): + w = RadioSelect() + self.assertEqual(w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> +<li><label><input checked="checked" type="radio" name="beatle" value="J" /> John</label></li> +<li><label><input type="radio" name="beatle" value="P" /> Paul</label></li> +<li><label><input type="radio" name="beatle" value="G" /> George</label></li> +<li><label><input type="radio" name="beatle" value="R" /> Ringo</label></li> +</ul>""") + + # If the value is None, none of the options are checked: + self.assertEqual(w.render('beatle', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> +<li><label><input type="radio" name="beatle" value="J" /> John</label></li> +<li><label><input type="radio" name="beatle" value="P" /> Paul</label></li> +<li><label><input type="radio" name="beatle" value="G" /> George</label></li> +<li><label><input type="radio" name="beatle" value="R" /> Ringo</label></li> +</ul>""") + + # If the value corresponds to a label (but not to an option value), none of the options are checked: + self.assertEqual(w.render('beatle', 'John', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> +<li><label><input type="radio" name="beatle" value="J" /> John</label></li> +<li><label><input type="radio" name="beatle" value="P" /> Paul</label></li> +<li><label><input type="radio" name="beatle" value="G" /> George</label></li> +<li><label><input type="radio" name="beatle" value="R" /> Ringo</label></li> +</ul>""") + + # The value is compared to its str(): + self.assertEqual(w.render('num', 2, choices=[('1', '1'), ('2', '2'), ('3', '3')]), """<ul> +<li><label><input type="radio" name="num" value="1" /> 1</label></li> +<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> +<li><label><input type="radio" name="num" value="3" /> 3</label></li> +</ul>""") + self.assertEqual(w.render('num', '2', choices=[(1, 1), (2, 2), (3, 3)]), """<ul> +<li><label><input type="radio" name="num" value="1" /> 1</label></li> +<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> +<li><label><input type="radio" name="num" value="3" /> 3</label></li> +</ul>""") + self.assertEqual(w.render('num', 2, choices=[(1, 1), (2, 2), (3, 3)]), """<ul> +<li><label><input type="radio" name="num" value="1" /> 1</label></li> +<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> +<li><label><input type="radio" name="num" value="3" /> 3</label></li> +</ul>""") + + # The 'choices' argument can be any iterable: + def get_choices(): + for i in range(5): + yield (i, i) + self.assertEqual(w.render('num', 2, choices=get_choices()), """<ul> +<li><label><input type="radio" name="num" value="0" /> 0</label></li> +<li><label><input type="radio" name="num" value="1" /> 1</label></li> +<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> +<li><label><input type="radio" name="num" value="3" /> 3</label></li> +<li><label><input type="radio" name="num" value="4" /> 4</label></li> +</ul>""") + + # You can also pass 'choices' to the constructor: + w = RadioSelect(choices=[(1, 1), (2, 2), (3, 3)]) + self.assertEqual(w.render('num', 2), """<ul> +<li><label><input type="radio" name="num" value="1" /> 1</label></li> +<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> +<li><label><input type="radio" name="num" value="3" /> 3</label></li> +</ul>""") + + # If 'choices' is passed to both the constructor and render(), then they'll both be in the output: + self.assertEqual(w.render('num', 2, choices=[(4, 4), (5, 5)]), """<ul> +<li><label><input type="radio" name="num" value="1" /> 1</label></li> +<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> +<li><label><input type="radio" name="num" value="3" /> 3</label></li> +<li><label><input type="radio" name="num" value="4" /> 4</label></li> +<li><label><input type="radio" name="num" value="5" /> 5</label></li> +</ul>""") + + # RadioSelect uses a RadioFieldRenderer to render the individual radio inputs. + # You can manipulate that object directly to customize the way the RadioSelect + # is rendered. + w = RadioSelect() + r = w.get_renderer('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) + inp_set1 = [] + inp_set2 = [] + inp_set3 = [] + inp_set4 = [] + + for inp in r: + inp_set1.append(str(inp)) + inp_set2.append('%s<br />' % inp) + inp_set3.append('<p>%s %s</p>' % (inp.tag(), inp.choice_label)) + inp_set4.append('%s %s %s %s %s' % (inp.name, inp.value, inp.choice_value, inp.choice_label, inp.is_checked())) + + self.assertEqual('\n'.join(inp_set1), """<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label> +<label><input type="radio" name="beatle" value="P" /> Paul</label> +<label><input type="radio" name="beatle" value="G" /> George</label> +<label><input type="radio" name="beatle" value="R" /> Ringo</label>""") + self.assertEqual('\n'.join(inp_set2), """<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label><br /> +<label><input type="radio" name="beatle" value="P" /> Paul</label><br /> +<label><input type="radio" name="beatle" value="G" /> George</label><br /> +<label><input type="radio" name="beatle" value="R" /> Ringo</label><br />""") + self.assertEqual('\n'.join(inp_set3), """<p><input checked="checked" type="radio" name="beatle" value="J" /> John</p> +<p><input type="radio" name="beatle" value="P" /> Paul</p> +<p><input type="radio" name="beatle" value="G" /> George</p> +<p><input type="radio" name="beatle" value="R" /> Ringo</p>""") + self.assertEqual('\n'.join(inp_set4), """beatle J J John True +beatle J P Paul False +beatle J G George False +beatle J R Ringo False""") + + # You can create your own custom renderers for RadioSelect to use. + class MyRenderer(RadioFieldRenderer): + def render(self): + return u'<br />\n'.join([unicode(choice) for choice in self]) + w = RadioSelect(renderer=MyRenderer) + self.assertEqual(w.render('beatle', 'G', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<label><input type="radio" name="beatle" value="J" /> John</label><br /> +<label><input type="radio" name="beatle" value="P" /> Paul</label><br /> +<label><input checked="checked" type="radio" name="beatle" value="G" /> George</label><br /> +<label><input type="radio" name="beatle" value="R" /> Ringo</label>""") + + # Or you can use custom RadioSelect fields that use your custom renderer. + class CustomRadioSelect(RadioSelect): + renderer = MyRenderer + w = CustomRadioSelect() + self.assertEqual(w.render('beatle', 'G', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<label><input type="radio" name="beatle" value="J" /> John</label><br /> +<label><input type="radio" name="beatle" value="P" /> Paul</label><br /> +<label><input checked="checked" type="radio" name="beatle" value="G" /> George</label><br /> +<label><input type="radio" name="beatle" value="R" /> Ringo</label>""") + + # A RadioFieldRenderer object also allows index access to individual RadioInput + w = RadioSelect() + r = w.get_renderer('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) + self.assertEqual(str(r[1]), '<label><input type="radio" name="beatle" value="P" /> Paul</label>') + self.assertEqual(str(r[0]), '<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label>') + self.assertTrue(r[0].is_checked()) + self.assertFalse(r[1].is_checked()) + self.assertEqual((r[1].name, r[1].value, r[1].choice_value, r[1].choice_label), ('beatle', u'J', u'P', u'Paul')) + + try: + r[10] + self.fail("This offset should not exist.") + except IndexError: + pass + + # Choices are escaped correctly + w = RadioSelect() + self.assertEqual(w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you > me')))), """<ul> +<li><label><input type="radio" name="escape" value="bad" /> you & me</label></li> +<li><label><input type="radio" name="escape" value="good" /> you > me</label></li> +</ul>""") + + # Unicode choices are correctly rendered as HTML + w = RadioSelect() + self.assertEqual(unicode(w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')])), u'<ul>\n<li><label><input checked="checked" type="radio" name="email" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" /> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label></li>\n<li><label><input type="radio" name="email" value="\u0107\u017e\u0161\u0111" /> abc\u0107\u017e\u0161\u0111</label></li>\n</ul>') + + # Attributes provided at instantiation are passed to the constituent inputs + w = RadioSelect(attrs={'id':'foo'}) + self.assertEqual(w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> +<li><label for="foo_0"><input checked="checked" type="radio" id="foo_0" value="J" name="beatle" /> John</label></li> +<li><label for="foo_1"><input type="radio" id="foo_1" value="P" name="beatle" /> Paul</label></li> +<li><label for="foo_2"><input type="radio" id="foo_2" value="G" name="beatle" /> George</label></li> +<li><label for="foo_3"><input type="radio" id="foo_3" value="R" name="beatle" /> Ringo</label></li> +</ul>""") + + # Attributes provided at render-time are passed to the constituent inputs + w = RadioSelect() + self.assertEqual(w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')), attrs={'id':'bar'}), """<ul> +<li><label for="bar_0"><input checked="checked" type="radio" id="bar_0" value="J" name="beatle" /> John</label></li> +<li><label for="bar_1"><input type="radio" id="bar_1" value="P" name="beatle" /> Paul</label></li> +<li><label for="bar_2"><input type="radio" id="bar_2" value="G" name="beatle" /> George</label></li> +<li><label for="bar_3"><input type="radio" id="bar_3" value="R" name="beatle" /> Ringo</label></li> +</ul>""") + + def test_checkboxselectmultiple(self): + w = CheckboxSelectMultiple() + self.assertEqual(w.render('beatles', ['J'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> +<li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li> +<li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> +<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> +<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> +</ul>""") + self.assertEqual(w.render('beatles', ['J', 'P'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> +<li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li> +<li><label><input checked="checked" type="checkbox" name="beatles" value="P" /> Paul</label></li> +<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> +<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> +</ul>""") + self.assertEqual(w.render('beatles', ['J', 'P', 'R'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> +<li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li> +<li><label><input checked="checked" type="checkbox" name="beatles" value="P" /> Paul</label></li> +<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> +<li><label><input checked="checked" type="checkbox" name="beatles" value="R" /> Ringo</label></li> +</ul>""") + + # If the value is None, none of the options are selected: + self.assertEqual(w.render('beatles', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> +<li><label><input type="checkbox" name="beatles" value="J" /> John</label></li> +<li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> +<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> +<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> +</ul>""") + + # If the value corresponds to a label (but not to an option value), none of the options are selected: + self.assertEqual(w.render('beatles', ['John'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> +<li><label><input type="checkbox" name="beatles" value="J" /> John</label></li> +<li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> +<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> +<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> +</ul>""") + + # If multiple values are given, but some of them are not valid, the valid ones are selected: + self.assertEqual(w.render('beatles', ['J', 'G', 'foo'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul> +<li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li> +<li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> +<li><label><input checked="checked" type="checkbox" name="beatles" value="G" /> George</label></li> +<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> +</ul>""") + + # The value is compared to its str(): + self.assertEqual(w.render('nums', [2], choices=[('1', '1'), ('2', '2'), ('3', '3')]), """<ul> +<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> +<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> +<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> +</ul>""") + self.assertEqual(w.render('nums', ['2'], choices=[(1, 1), (2, 2), (3, 3)]), """<ul> +<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> +<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> +<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> +</ul>""") + self.assertEqual(w.render('nums', [2], choices=[(1, 1), (2, 2), (3, 3)]), """<ul> +<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> +<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> +<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> +</ul>""") + + # The 'choices' argument can be any iterable: + def get_choices(): + for i in range(5): + yield (i, i) + self.assertEqual(w.render('nums', [2], choices=get_choices()), """<ul> +<li><label><input type="checkbox" name="nums" value="0" /> 0</label></li> +<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> +<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> +<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> +<li><label><input type="checkbox" name="nums" value="4" /> 4</label></li> +</ul>""") + + # You can also pass 'choices' to the constructor: + w = CheckboxSelectMultiple(choices=[(1, 1), (2, 2), (3, 3)]) + self.assertEqual(w.render('nums', [2]), """<ul> +<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> +<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> +<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> +</ul>""") + + # If 'choices' is passed to both the constructor and render(), then they'll both be in the output: + self.assertEqual(w.render('nums', [2], choices=[(4, 4), (5, 5)]), """<ul> +<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> +<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> +<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> +<li><label><input type="checkbox" name="nums" value="4" /> 4</label></li> +<li><label><input type="checkbox" name="nums" value="5" /> 5</label></li> +</ul>""") + + # Choices are escaped correctly + self.assertEqual(w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you > me')))), """<ul> +<li><label><input type="checkbox" name="escape" value="1" /> 1</label></li> +<li><label><input type="checkbox" name="escape" value="2" /> 2</label></li> +<li><label><input type="checkbox" name="escape" value="3" /> 3</label></li> +<li><label><input type="checkbox" name="escape" value="bad" /> you & me</label></li> +<li><label><input type="checkbox" name="escape" value="good" /> you > me</label></li> +</ul>""") + + # Test the usage of _has_changed + self.assertFalse(w._has_changed(None, None)) + self.assertFalse(w._has_changed([], None)) + self.assertTrue(w._has_changed(None, [u'1'])) + self.assertFalse(w._has_changed([1, 2], [u'1', u'2'])) + self.assertTrue(w._has_changed([1, 2], [u'1'])) + self.assertTrue(w._has_changed([1, 2], [u'1', u'3'])) + + # Unicode choices are correctly rendered as HTML + self.assertEqual(w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), u'<ul>\n<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li>\n<li><label><input type="checkbox" name="nums" value="2" /> 2</label></li>\n<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li>\n<li><label><input checked="checked" type="checkbox" name="nums" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" /> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label></li>\n<li><label><input type="checkbox" name="nums" value="\u0107\u017e\u0161\u0111" /> abc\u0107\u017e\u0161\u0111</label></li>\n</ul>') + + # Each input gets a separate ID + self.assertEqual(CheckboxSelectMultiple().render('letters', list('ac'), choices=zip(list('abc'), list('ABC')), attrs={'id': 'abc'}), """<ul> +<li><label for="abc_0"><input checked="checked" type="checkbox" name="letters" value="a" id="abc_0" /> A</label></li> +<li><label for="abc_1"><input type="checkbox" name="letters" value="b" id="abc_1" /> B</label></li> +<li><label for="abc_2"><input checked="checked" type="checkbox" name="letters" value="c" id="abc_2" /> C</label></li> +</ul>""") + + def test_multi(self): + class MyMultiWidget(MultiWidget): + def decompress(self, value): + if value: + return value.split('__') + return ['', ''] + def format_output(self, rendered_widgets): + return u'<br />'.join(rendered_widgets) + + w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'}))) + self.assertEqual(w.render('name', ['john', 'lennon']), u'<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />') + self.assertEqual(w.render('name', 'john__lennon'), u'<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />') + self.assertEqual(w.render('name', 'john__lennon', attrs={'id':'foo'}), u'<input id="foo_0" type="text" class="big" value="john" name="name_0" /><br /><input id="foo_1" type="text" class="small" value="lennon" name="name_1" />') + w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'})), attrs={'id': 'bar'}) + self.assertEqual(w.render('name', ['john', 'lennon']), u'<input id="bar_0" type="text" class="big" value="john" name="name_0" /><br /><input id="bar_1" type="text" class="small" value="lennon" name="name_1" />') + + w = MyMultiWidget(widgets=(TextInput(), TextInput())) + + # test with no initial data + self.assertTrue(w._has_changed(None, [u'john', u'lennon'])) + + # test when the data is the same as initial + self.assertFalse(w._has_changed(u'john__lennon', [u'john', u'lennon'])) + + # test when the first widget's data has changed + self.assertTrue(w._has_changed(u'john__lennon', [u'alfred', u'lennon'])) + + # test when the last widget's data has changed. this ensures that it is not + # short circuiting while testing the widgets. + self.assertTrue(w._has_changed(u'john__lennon', [u'john', u'denver'])) + + def test_splitdatetime(self): + w = SplitDateTimeWidget() + self.assertEqual(w.render('date', ''), u'<input type="text" name="date_0" /><input type="text" name="date_1" />') + self.assertEqual(w.render('date', None), u'<input type="text" name="date_0" /><input type="text" name="date_1" />') + self.assertEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), u'<input type="text" name="date_0" value="2006-01-10" /><input type="text" name="date_1" value="07:30:00" />') + self.assertEqual(w.render('date', [datetime.date(2006, 1, 10), datetime.time(7, 30)]), u'<input type="text" name="date_0" value="2006-01-10" /><input type="text" name="date_1" value="07:30:00" />') + + # You can also pass 'attrs' to the constructor. In this case, the attrs will be + w = SplitDateTimeWidget(attrs={'class': 'pretty'}) + self.assertEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), u'<input type="text" class="pretty" value="2006-01-10" name="date_0" /><input type="text" class="pretty" value="07:30:00" name="date_1" />') + + # Use 'date_format' and 'time_format' to change the way a value is displayed. + w = SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M') + self.assertEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), u'<input type="text" name="date_0" value="10/01/2006" /><input type="text" name="date_1" value="07:30" />') + + self.assertTrue(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'2008-05-06', u'12:40:00'])) + self.assertFalse(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'06/05/2008', u'12:40'])) + self.assertTrue(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'06/05/2008', u'12:41'])) + + def test_datetimeinput(self): + w = DateTimeInput() + self.assertEqual(w.render('date', None), u'<input type="text" name="date" />') + d = datetime.datetime(2007, 9, 17, 12, 51, 34, 482548) + self.assertEqual(str(d), '2007-09-17 12:51:34.482548') + + # The microseconds are trimmed on display, by default. + self.assertEqual(w.render('date', d), u'<input type="text" name="date" value="2007-09-17 12:51:34" />') + self.assertEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51, 34)), u'<input type="text" name="date" value="2007-09-17 12:51:34" />') + self.assertEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), u'<input type="text" name="date" value="2007-09-17 12:51:00" />') + + # Use 'format' to change the way a value is displayed. + w = DateTimeInput(format='%d/%m/%Y %H:%M') + self.assertEqual(w.render('date', d), u'<input type="text" name="date" value="17/09/2007 12:51" />') + self.assertFalse(w._has_changed(d, '17/09/2007 12:51')) + + # Make sure a custom format works with _has_changed. The hidden input will use + data = datetime.datetime(2010, 3, 6, 12, 0, 0) + custom_format = '%d.%m.%Y %H:%M' + w = DateTimeInput(format=custom_format) + self.assertFalse(w._has_changed(formats.localize_input(data), data.strftime(custom_format))) + + def test_dateinput(self): + w = DateInput() + self.assertEqual(w.render('date', None), u'<input type="text" name="date" />') + d = datetime.date(2007, 9, 17) + self.assertEqual(str(d), '2007-09-17') + + self.assertEqual(w.render('date', d), u'<input type="text" name="date" value="2007-09-17" />') + self.assertEqual(w.render('date', datetime.date(2007, 9, 17)), u'<input type="text" name="date" value="2007-09-17" />') + + # We should be able to initialize from a unicode value. + self.assertEqual(w.render('date', u'2007-09-17'), u'<input type="text" name="date" value="2007-09-17" />') + + # Use 'format' to change the way a value is displayed. + w = DateInput(format='%d/%m/%Y') + self.assertEqual(w.render('date', d), u'<input type="text" name="date" value="17/09/2007" />') + self.assertFalse(w._has_changed(d, '17/09/2007')) + + # Make sure a custom format works with _has_changed. The hidden input will use + data = datetime.date(2010, 3, 6) + custom_format = '%d.%m.%Y' + w = DateInput(format=custom_format) + self.assertFalse(w._has_changed(formats.localize_input(data), data.strftime(custom_format))) + + def test_timeinput(self): + w = TimeInput() + self.assertEqual(w.render('time', None), u'<input type="text" name="time" />') + t = datetime.time(12, 51, 34, 482548) + self.assertEqual(str(t), '12:51:34.482548') + + # The microseconds are trimmed on display, by default. + self.assertEqual(w.render('time', t), u'<input type="text" name="time" value="12:51:34" />') + self.assertEqual(w.render('time', datetime.time(12, 51, 34)), u'<input type="text" name="time" value="12:51:34" />') + self.assertEqual(w.render('time', datetime.time(12, 51)), u'<input type="text" name="time" value="12:51:00" />') + + # We should be able to initialize from a unicode value. + self.assertEqual(w.render('time', u'13:12:11'), u'<input type="text" name="time" value="13:12:11" />') + + # Use 'format' to change the way a value is displayed. + w = TimeInput(format='%H:%M') + self.assertEqual(w.render('time', t), u'<input type="text" name="time" value="12:51" />') + self.assertFalse(w._has_changed(t, '12:51')) + + # Make sure a custom format works with _has_changed. The hidden input will use + data = datetime.time(13, 0) + custom_format = '%I:%M %p' + w = TimeInput(format=custom_format) + self.assertFalse(w._has_changed(formats.localize_input(data), data.strftime(custom_format))) + + def test_splithiddendatetime(self): + from django.forms.widgets import SplitHiddenDateTimeWidget + + w = SplitHiddenDateTimeWidget() + self.assertEqual(w.render('date', ''), u'<input type="hidden" name="date_0" /><input type="hidden" name="date_1" />') + d = datetime.datetime(2007, 9, 17, 12, 51, 34, 482548) + self.assertEqual(str(d), '2007-09-17 12:51:34.482548') + self.assertEqual(w.render('date', d), u'<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:34" />') + self.assertEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51, 34)), u'<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:34" />') + self.assertEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), u'<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:00" />') + + +class FormsI18NWidgetsTestCase(TestCase): + def setUp(self): + super(FormsI18NWidgetsTestCase, self).setUp() + self.old_use_l10n = getattr(settings, 'USE_L10N', False) + settings.USE_L10N = True + activate('de-at') + + def tearDown(self): + deactivate() + settings.USE_L10N = self.old_use_l10n + super(FormsI18NWidgetsTestCase, self).tearDown() + + def test_splitdatetime(self): + w = SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M') + self.assertTrue(w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'06.05.2008', u'12:41'])) + + def test_datetimeinput(self): + w = DateTimeInput() + d = datetime.datetime(2007, 9, 17, 12, 51, 34, 482548) + w.is_localized = True + self.assertEqual(w.render('date', d), u'<input type="text" name="date" value="17.09.2007 12:51:34" />') + + def test_dateinput(self): + w = DateInput() + d = datetime.date(2007, 9, 17) + w.is_localized = True + self.assertEqual(w.render('date', d), u'<input type="text" name="date" value="17.09.2007" />') + + def test_timeinput(self): + w = TimeInput() + t = datetime.time(12, 51, 34, 482548) + w.is_localized = True + self.assertEqual(w.render('time', t), u'<input type="text" name="time" value="12:51:34" />') + + def test_splithiddendatetime(self): + from django.forms.widgets import SplitHiddenDateTimeWidget + + w = SplitHiddenDateTimeWidget() + w.is_localized = True + self.assertEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), u'<input type="hidden" name="date_0" value="17.09.2007" /><input type="hidden" name="date_1" value="12:51:00" />') + + +class SelectAndTextWidget(MultiWidget): + """ + MultiWidget subclass + """ + def __init__(self, choices=[]): + widgets = [ + RadioSelect(choices=choices), + TextInput + ] + super(SelectAndTextWidget, self).__init__(widgets) + + def _set_choices(self, choices): + """ + When choices are set for this widget, we want to pass those along to the Select widget + """ + self.widgets[0].choices = choices + def _get_choices(self): + """ + The choices for this widget are the Select widget's choices + """ + return self.widgets[0].choices + choices = property(_get_choices, _set_choices) + + +class WidgetTests(TestCase): + def test_12048(self): + # See ticket #12048. + w1 = SelectAndTextWidget(choices=[1,2,3]) + w2 = copy.deepcopy(w1) + w2.choices = [4,5,6] + # w2 ought to be independent of w1, since MultiWidget ought + # to make a copy of its sub-widgets when it is copied. + self.assertEqual(w1.choices, [1,2,3]) + + def test_13390(self): + # See ticket #13390 + class SplitDateForm(Form): + field = DateTimeField(widget=SplitDateTimeWidget, required=False) + + form = SplitDateForm({'field': ''}) + self.assertTrue(form.is_valid()) + form = SplitDateForm({'field': ['', '']}) + self.assertTrue(form.is_valid()) + + class SplitDateRequiredForm(Form): + field = DateTimeField(widget=SplitDateTimeWidget, required=True) + + form = SplitDateRequiredForm({'field': ''}) + self.assertFalse(form.is_valid()) + form = SplitDateRequiredForm({'field': ['', '']}) + self.assertFalse(form.is_valid()) + + +class FakeFieldFile(object): + """ + Quacks like a FieldFile (has a .url and unicode representation), but + doesn't require us to care about storages etc. + + """ + url = 'something' + + def __unicode__(self): + return self.url + +class ClearableFileInputTests(TestCase): + def test_clear_input_renders(self): + """ + A ClearableFileInput with is_required False and rendered with + an initial value that is a file renders a clear checkbox. + + """ + widget = ClearableFileInput() + widget.is_required = False + self.assertEqual(widget.render('myfile', FakeFieldFile()), + u'Currently: <a target="_blank" href="something">something</a> <input type="checkbox" name="myfile-clear" id="myfile-clear_id" /> <label for="myfile-clear_id">Clear</label><br />Change: <input type="file" name="myfile" />') + + def test_clear_input_renders_only_if_not_required(self): + """ + A ClearableFileInput with is_required=False does not render a clear + checkbox. + + """ + widget = ClearableFileInput() + widget.is_required = True + self.assertEqual(widget.render('myfile', FakeFieldFile()), + u'Currently: <a target="_blank" href="something">something</a> <br />Change: <input type="file" name="myfile" />') + + def test_clear_input_renders_only_if_initial(self): + """ + A ClearableFileInput instantiated with no initial value does not render + a clear checkbox. + + """ + widget = ClearableFileInput() + widget.is_required = False + self.assertEqual(widget.render('myfile', None), + u'<input type="file" name="myfile" />') + + def test_clear_input_checked_returns_false(self): + """ + ClearableFileInput.value_from_datadict returns False if the clear + checkbox is checked, if not required. + + """ + widget = ClearableFileInput() + widget.is_required = False + self.assertEqual(widget.value_from_datadict( + data={'myfile-clear': True}, + files={}, + name='myfile'), False) + + def test_clear_input_checked_returns_false_only_if_not_required(self): + """ + ClearableFileInput.value_from_datadict never returns False if the field + is required. + + """ + widget = ClearableFileInput() + widget.is_required = True + f = SimpleUploadedFile('something.txt', 'content') + self.assertEqual(widget.value_from_datadict( + data={'myfile-clear': True}, + files={'myfile': f}, + name='myfile'), f) diff --git a/tests/regressiontests/forms/util.py b/tests/regressiontests/forms/util.py deleted file mode 100644 index f365c8c1ae..0000000000 --- a/tests/regressiontests/forms/util.py +++ /dev/null @@ -1,60 +0,0 @@ -# coding: utf-8 -""" -Tests for forms/util.py module. -""" - -tests = r""" ->>> from django.forms.util import * ->>> from django.core.exceptions import ValidationError ->>> from django.utils.translation import ugettext_lazy - -########### -# flatatt # -########### - ->>> from django.forms.util import flatatt ->>> flatatt({'id': "header"}) -u' id="header"' ->>> flatatt({'class': "news", 'title': "Read this"}) -u' class="news" title="Read this"' ->>> flatatt({}) -u'' - -################### -# ValidationError # -################### - -# Can take a string. ->>> print ErrorList(ValidationError("There was an error.").messages) -<ul class="errorlist"><li>There was an error.</li></ul> - -# Can take a unicode string. ->>> print ErrorList(ValidationError(u"Not \u03C0.").messages) -<ul class="errorlist"><li>Not π.</li></ul> - -# Can take a lazy string. ->>> print ErrorList(ValidationError(ugettext_lazy("Error.")).messages) -<ul class="errorlist"><li>Error.</li></ul> - -# Can take a list. ->>> print ErrorList(ValidationError(["Error one.", "Error two."]).messages) -<ul class="errorlist"><li>Error one.</li><li>Error two.</li></ul> - -# Can take a mixture in a list. ->>> print ErrorList(ValidationError(["First error.", u"Not \u03C0.", ugettext_lazy("Error.")]).messages) -<ul class="errorlist"><li>First error.</li><li>Not π.</li><li>Error.</li></ul> - ->>> class VeryBadError: -... def __unicode__(self): return u"A very bad error." - -# Can take a non-string. ->>> print ErrorList(ValidationError(VeryBadError()).messages) -<ul class="errorlist"><li>A very bad error.</li></ul> - -# Escapes non-safe input but not input marked safe. ->>> example = 'Example of link: <a href="http://www.example.com/">example</a>' ->>> print ErrorList([example]) -<ul class="errorlist"><li>Example of link: <a href="http://www.example.com/">example</a></li></ul> ->>> print ErrorList([mark_safe(example)]) -<ul class="errorlist"><li>Example of link: <a href="http://www.example.com/">example</a></li></ul> -""" diff --git a/tests/regressiontests/forms/widgets.py b/tests/regressiontests/forms/widgets.py deleted file mode 100644 index 2c21d197b2..0000000000 --- a/tests/regressiontests/forms/widgets.py +++ /dev/null @@ -1,1398 +0,0 @@ -# -*- coding: utf-8 -*- -tests = r""" ->>> from django.forms import * ->>> from django.forms.widgets import RadioFieldRenderer ->>> from django.utils.safestring import mark_safe ->>> from django.utils import formats ->>> import datetime ->>> import time ->>> import re ->>> from decimal import Decimal ->>> from django.utils.translation import activate, deactivate ->>> from django.conf import settings - -########### -# Widgets # -########### - -Each Widget class corresponds to an HTML form widget. A Widget knows how to -render itself, given a field name and some data. Widgets don't perform -validation. - -# TextInput Widget ############################################################ - ->>> w = TextInput() ->>> w.render('email', '') -u'<input type="text" name="email" />' ->>> w.render('email', None) -u'<input type="text" name="email" />' ->>> w.render('email', 'test@example.com') -u'<input type="text" name="email" value="test@example.com" />' ->>> w.render('email', 'some "quoted" & ampersanded value') -u'<input type="text" name="email" value="some "quoted" & ampersanded value" />' ->>> w.render('email', 'test@example.com', attrs={'class': 'fun'}) -u'<input type="text" name="email" value="test@example.com" class="fun" />' - -# Note that doctest in Python 2.4 (and maybe 2.5?) doesn't support non-ascii -# characters in output, so we're displaying the repr() here. ->>> w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}) -u'<input type="text" name="email" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" class="fun" />' - -You can also pass 'attrs' to the constructor: ->>> w = TextInput(attrs={'class': 'fun'}) ->>> w.render('email', '') -u'<input type="text" class="fun" name="email" />' ->>> w.render('email', 'foo@example.com') -u'<input type="text" class="fun" value="foo@example.com" name="email" />' - -'attrs' passed to render() get precedence over those passed to the constructor: ->>> w = TextInput(attrs={'class': 'pretty'}) ->>> w.render('email', '', attrs={'class': 'special'}) -u'<input type="text" class="special" name="email" />' - -'attrs' can be safe-strings if needed ->>> w = TextInput(attrs={'onBlur': mark_safe("function('foo')")}) ->>> print w.render('email', '') -<input onBlur="function('foo')" type="text" name="email" /> - -# PasswordInput Widget ############################################################ - ->>> w = PasswordInput() ->>> w.render('email', '') -u'<input type="password" name="email" />' ->>> w.render('email', None) -u'<input type="password" name="email" />' ->>> w.render('email', 'secret') -u'<input type="password" name="email" />' - -The render_value argument lets you specify whether the widget should render -its value. For security reasons, this is off by default. - ->>> w = PasswordInput(render_value=True) ->>> w.render('email', '') -u'<input type="password" name="email" />' ->>> w.render('email', None) -u'<input type="password" name="email" />' ->>> w.render('email', 'test@example.com') -u'<input type="password" name="email" value="test@example.com" />' ->>> w.render('email', 'some "quoted" & ampersanded value') -u'<input type="password" name="email" value="some "quoted" & ampersanded value" />' ->>> w.render('email', 'test@example.com', attrs={'class': 'fun'}) -u'<input type="password" name="email" value="test@example.com" class="fun" />' - -You can also pass 'attrs' to the constructor: ->>> w = PasswordInput(attrs={'class': 'fun'}, render_value=True) ->>> w.render('email', '') -u'<input type="password" class="fun" name="email" />' ->>> w.render('email', 'foo@example.com') -u'<input type="password" class="fun" value="foo@example.com" name="email" />' - -'attrs' passed to render() get precedence over those passed to the constructor: ->>> w = PasswordInput(attrs={'class': 'pretty'}, render_value=True) ->>> w.render('email', '', attrs={'class': 'special'}) -u'<input type="password" class="special" name="email" />' - ->>> w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}) -u'<input type="password" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />' - -# HiddenInput Widget ############################################################ - ->>> w = HiddenInput() ->>> w.render('email', '') -u'<input type="hidden" name="email" />' ->>> w.render('email', None) -u'<input type="hidden" name="email" />' ->>> w.render('email', 'test@example.com') -u'<input type="hidden" name="email" value="test@example.com" />' ->>> w.render('email', 'some "quoted" & ampersanded value') -u'<input type="hidden" name="email" value="some "quoted" & ampersanded value" />' ->>> w.render('email', 'test@example.com', attrs={'class': 'fun'}) -u'<input type="hidden" name="email" value="test@example.com" class="fun" />' - -You can also pass 'attrs' to the constructor: ->>> w = HiddenInput(attrs={'class': 'fun'}) ->>> w.render('email', '') -u'<input type="hidden" class="fun" name="email" />' ->>> w.render('email', 'foo@example.com') -u'<input type="hidden" class="fun" value="foo@example.com" name="email" />' - -'attrs' passed to render() get precedence over those passed to the constructor: ->>> w = HiddenInput(attrs={'class': 'pretty'}) ->>> w.render('email', '', attrs={'class': 'special'}) -u'<input type="hidden" class="special" name="email" />' - ->>> w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}) -u'<input type="hidden" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />' - -'attrs' passed to render() get precedence over those passed to the constructor: ->>> w = HiddenInput(attrs={'class': 'pretty'}) ->>> w.render('email', '', attrs={'class': 'special'}) -u'<input type="hidden" class="special" name="email" />' - -Boolean values are rendered to their string forms ("True" and "False"). ->>> w = HiddenInput() ->>> w.render('get_spam', False) -u'<input type="hidden" name="get_spam" value="False" />' ->>> w.render('get_spam', True) -u'<input type="hidden" name="get_spam" value="True" />' - -# MultipleHiddenInput Widget ################################################## - ->>> w = MultipleHiddenInput() ->>> w.render('email', []) -u'' ->>> w.render('email', None) -u'' ->>> w.render('email', ['test@example.com']) -u'<input type="hidden" name="email" value="test@example.com" />' ->>> w.render('email', ['some "quoted" & ampersanded value']) -u'<input type="hidden" name="email" value="some "quoted" & ampersanded value" />' ->>> w.render('email', ['test@example.com', 'foo@example.com']) -u'<input type="hidden" name="email" value="test@example.com" />\n<input type="hidden" name="email" value="foo@example.com" />' ->>> w.render('email', ['test@example.com'], attrs={'class': 'fun'}) -u'<input type="hidden" name="email" value="test@example.com" class="fun" />' ->>> w.render('email', ['test@example.com', 'foo@example.com'], attrs={'class': 'fun'}) -u'<input type="hidden" name="email" value="test@example.com" class="fun" />\n<input type="hidden" name="email" value="foo@example.com" class="fun" />' - -You can also pass 'attrs' to the constructor: ->>> w = MultipleHiddenInput(attrs={'class': 'fun'}) ->>> w.render('email', []) -u'' ->>> w.render('email', ['foo@example.com']) -u'<input type="hidden" class="fun" value="foo@example.com" name="email" />' ->>> w.render('email', ['foo@example.com', 'test@example.com']) -u'<input type="hidden" class="fun" value="foo@example.com" name="email" />\n<input type="hidden" class="fun" value="test@example.com" name="email" />' - -'attrs' passed to render() get precedence over those passed to the constructor: ->>> w = MultipleHiddenInput(attrs={'class': 'pretty'}) ->>> w.render('email', ['foo@example.com'], attrs={'class': 'special'}) -u'<input type="hidden" class="special" value="foo@example.com" name="email" />' - ->>> w.render('email', ['ŠĐĆŽćžšđ'], attrs={'class': 'fun'}) -u'<input type="hidden" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />' - -'attrs' passed to render() get precedence over those passed to the constructor: ->>> w = MultipleHiddenInput(attrs={'class': 'pretty'}) ->>> w.render('email', ['foo@example.com'], attrs={'class': 'special'}) -u'<input type="hidden" class="special" value="foo@example.com" name="email" />' - -Each input gets a separate ID. ->>> w = MultipleHiddenInput() ->>> w.render('letters', list('abc'), attrs={'id': 'hideme'}) -u'<input type="hidden" name="letters" value="a" id="hideme_0" />\n<input type="hidden" name="letters" value="b" id="hideme_1" />\n<input type="hidden" name="letters" value="c" id="hideme_2" />' - -# FileInput Widget ############################################################ - -FileInput widgets don't ever show the value, because the old value is of no use -if you are updating the form or if the provided file generated an error. ->>> w = FileInput() ->>> w.render('email', '') -u'<input type="file" name="email" />' ->>> w.render('email', None) -u'<input type="file" name="email" />' ->>> w.render('email', 'test@example.com') -u'<input type="file" name="email" />' ->>> w.render('email', 'some "quoted" & ampersanded value') -u'<input type="file" name="email" />' ->>> w.render('email', 'test@example.com', attrs={'class': 'fun'}) -u'<input type="file" name="email" class="fun" />' - -You can also pass 'attrs' to the constructor: ->>> w = FileInput(attrs={'class': 'fun'}) ->>> w.render('email', '') -u'<input type="file" class="fun" name="email" />' ->>> w.render('email', 'foo@example.com') -u'<input type="file" class="fun" name="email" />' - ->>> w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}) -u'<input type="file" class="fun" name="email" />' - -Test for the behavior of _has_changed for FileInput. The value of data will -more than likely come from request.FILES. The value of initial data will -likely be a filename stored in the database. Since its value is of no use to -a FileInput it is ignored. - ->>> w = FileInput() - -# No file was uploaded and no initial data. ->>> w._has_changed(u'', None) -False - -# A file was uploaded and no initial data. ->>> w._has_changed(u'', {'filename': 'resume.txt', 'content': 'My resume'}) -True - -# A file was not uploaded, but there is initial data ->>> w._has_changed(u'resume.txt', None) -False - -# A file was uploaded and there is initial data (file identity is not dealt -# with here) ->>> w._has_changed('resume.txt', {'filename': 'resume.txt', 'content': 'My resume'}) -True - -# Textarea Widget ############################################################# - ->>> w = Textarea() ->>> w.render('msg', '') -u'<textarea rows="10" cols="40" name="msg"></textarea>' ->>> w.render('msg', None) -u'<textarea rows="10" cols="40" name="msg"></textarea>' ->>> w.render('msg', 'value') -u'<textarea rows="10" cols="40" name="msg">value</textarea>' ->>> w.render('msg', 'some "quoted" & ampersanded value') -u'<textarea rows="10" cols="40" name="msg">some "quoted" & ampersanded value</textarea>' ->>> w.render('msg', mark_safe('pre "quoted" value')) -u'<textarea rows="10" cols="40" name="msg">pre "quoted" value</textarea>' ->>> w.render('msg', 'value', attrs={'class': 'pretty', 'rows': 20}) -u'<textarea class="pretty" rows="20" cols="40" name="msg">value</textarea>' - -You can also pass 'attrs' to the constructor: ->>> w = Textarea(attrs={'class': 'pretty'}) ->>> w.render('msg', '') -u'<textarea rows="10" cols="40" name="msg" class="pretty"></textarea>' ->>> w.render('msg', 'example') -u'<textarea rows="10" cols="40" name="msg" class="pretty">example</textarea>' - -'attrs' passed to render() get precedence over those passed to the constructor: ->>> w = Textarea(attrs={'class': 'pretty'}) ->>> w.render('msg', '', attrs={'class': 'special'}) -u'<textarea rows="10" cols="40" name="msg" class="special"></textarea>' - ->>> w.render('msg', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}) -u'<textarea rows="10" cols="40" name="msg" class="fun">\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111</textarea>' - -# CheckboxInput Widget ######################################################## - ->>> w = CheckboxInput() ->>> w.render('is_cool', '') -u'<input type="checkbox" name="is_cool" />' ->>> w.render('is_cool', None) -u'<input type="checkbox" name="is_cool" />' ->>> w.render('is_cool', False) -u'<input type="checkbox" name="is_cool" />' ->>> w.render('is_cool', True) -u'<input checked="checked" type="checkbox" name="is_cool" />' - -Using any value that's not in ('', None, False, True) will check the checkbox -and set the 'value' attribute. ->>> w.render('is_cool', 'foo') -u'<input checked="checked" type="checkbox" name="is_cool" value="foo" />' - ->>> w.render('is_cool', False, attrs={'class': 'pretty'}) -u'<input type="checkbox" name="is_cool" class="pretty" />' - -You can also pass 'attrs' to the constructor: ->>> w = CheckboxInput(attrs={'class': 'pretty'}) ->>> w.render('is_cool', '') -u'<input type="checkbox" class="pretty" name="is_cool" />' - -'attrs' passed to render() get precedence over those passed to the constructor: ->>> w = CheckboxInput(attrs={'class': 'pretty'}) ->>> w.render('is_cool', '', attrs={'class': 'special'}) -u'<input type="checkbox" class="special" name="is_cool" />' - -You can pass 'check_test' to the constructor. This is a callable that takes the -value and returns True if the box should be checked. ->>> w = CheckboxInput(check_test=lambda value: value.startswith('hello')) ->>> w.render('greeting', '') -u'<input type="checkbox" name="greeting" />' ->>> w.render('greeting', 'hello') -u'<input checked="checked" type="checkbox" name="greeting" value="hello" />' ->>> w.render('greeting', 'hello there') -u'<input checked="checked" type="checkbox" name="greeting" value="hello there" />' ->>> w.render('greeting', 'hello & goodbye') -u'<input checked="checked" type="checkbox" name="greeting" value="hello & goodbye" />' - -A subtlety: If the 'check_test' argument cannot handle a value and raises any -exception during its __call__, then the exception will be swallowed and the box -will not be checked. In this example, the 'check_test' assumes the value has a -startswith() method, which fails for the values True, False and None. ->>> w.render('greeting', True) -u'<input type="checkbox" name="greeting" />' ->>> w.render('greeting', False) -u'<input type="checkbox" name="greeting" />' ->>> w.render('greeting', None) -u'<input type="checkbox" name="greeting" />' - -The CheckboxInput widget will return False if the key is not found in the data -dictionary (because HTML form submission doesn't send any result for unchecked -checkboxes). ->>> w.value_from_datadict({}, {}, 'testing') -False - ->>> w._has_changed(None, None) -False ->>> w._has_changed(None, u'') -False ->>> w._has_changed(u'', None) -False ->>> w._has_changed(u'', u'') -False ->>> w._has_changed(False, u'on') -True ->>> w._has_changed(True, u'on') -False ->>> w._has_changed(True, u'') -True - -# Select Widget ############################################################### - ->>> w = Select() ->>> print w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<select name="beatle"> -<option value="J" selected="selected">John</option> -<option value="P">Paul</option> -<option value="G">George</option> -<option value="R">Ringo</option> -</select> - -If the value is None, none of the options are selected: ->>> print w.render('beatle', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<select name="beatle"> -<option value="J">John</option> -<option value="P">Paul</option> -<option value="G">George</option> -<option value="R">Ringo</option> -</select> - -If the value corresponds to a label (but not to an option value), none of the options are selected: ->>> print w.render('beatle', 'John', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<select name="beatle"> -<option value="J">John</option> -<option value="P">Paul</option> -<option value="G">George</option> -<option value="R">Ringo</option> -</select> - -The value is compared to its str(): ->>> print w.render('num', 2, choices=[('1', '1'), ('2', '2'), ('3', '3')]) -<select name="num"> -<option value="1">1</option> -<option value="2" selected="selected">2</option> -<option value="3">3</option> -</select> ->>> print w.render('num', '2', choices=[(1, 1), (2, 2), (3, 3)]) -<select name="num"> -<option value="1">1</option> -<option value="2" selected="selected">2</option> -<option value="3">3</option> -</select> ->>> print w.render('num', 2, choices=[(1, 1), (2, 2), (3, 3)]) -<select name="num"> -<option value="1">1</option> -<option value="2" selected="selected">2</option> -<option value="3">3</option> -</select> - -The 'choices' argument can be any iterable: ->>> from itertools import chain ->>> def get_choices(): -... for i in range(5): -... yield (i, i) ->>> print w.render('num', 2, choices=get_choices()) -<select name="num"> -<option value="0">0</option> -<option value="1">1</option> -<option value="2" selected="selected">2</option> -<option value="3">3</option> -<option value="4">4</option> -</select> ->>> things = ({'id': 1, 'name': 'And Boom'}, {'id': 2, 'name': 'One More Thing!'}) ->>> class SomeForm(Form): -... somechoice = ChoiceField(choices=chain((('', '-'*9),), [(thing['id'], thing['name']) for thing in things])) ->>> f = SomeForm() ->>> f.as_table() -u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>' ->>> f.as_table() -u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>' ->>> f = SomeForm({'somechoice': 2}) ->>> f.as_table() -u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="">---------</option>\n<option value="1">And Boom</option>\n<option value="2" selected="selected">One More Thing!</option>\n</select></td></tr>' - -You can also pass 'choices' to the constructor: ->>> w = Select(choices=[(1, 1), (2, 2), (3, 3)]) ->>> print w.render('num', 2) -<select name="num"> -<option value="1">1</option> -<option value="2" selected="selected">2</option> -<option value="3">3</option> -</select> - -If 'choices' is passed to both the constructor and render(), then they'll both be in the output: ->>> print w.render('num', 2, choices=[(4, 4), (5, 5)]) -<select name="num"> -<option value="1">1</option> -<option value="2" selected="selected">2</option> -<option value="3">3</option> -<option value="4">4</option> -<option value="5">5</option> -</select> - -# Choices are escaped correctly ->>> print w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you > me')))) -<select name="escape"> -<option value="1">1</option> -<option value="2">2</option> -<option value="3">3</option> -<option value="bad">you & me</option> -<option value="good">you > me</option> -</select> - -# Unicode choices are correctly rendered as HTML ->>> w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]) -u'<select name="email">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected="selected">\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</option>\n<option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>\n</select>' - -If choices is passed to the constructor and is a generator, it can be iterated -over multiple times without getting consumed: ->>> w = Select(choices=get_choices()) ->>> print w.render('num', 2) -<select name="num"> -<option value="0">0</option> -<option value="1">1</option> -<option value="2" selected="selected">2</option> -<option value="3">3</option> -<option value="4">4</option> -</select> ->>> print w.render('num', 3) -<select name="num"> -<option value="0">0</option> -<option value="1">1</option> -<option value="2">2</option> -<option value="3" selected="selected">3</option> -<option value="4">4</option> -</select> - -Choices can be nested one level in order to create HTML optgroups: ->>> w.choices=(('outer1', 'Outer 1'), ('Group "1"', (('inner1', 'Inner 1'), ('inner2', 'Inner 2')))) ->>> print w.render('nestchoice', None) -<select name="nestchoice"> -<option value="outer1">Outer 1</option> -<optgroup label="Group "1""> -<option value="inner1">Inner 1</option> -<option value="inner2">Inner 2</option> -</optgroup> -</select> - ->>> print w.render('nestchoice', 'outer1') -<select name="nestchoice"> -<option value="outer1" selected="selected">Outer 1</option> -<optgroup label="Group "1""> -<option value="inner1">Inner 1</option> -<option value="inner2">Inner 2</option> -</optgroup> -</select> - ->>> print w.render('nestchoice', 'inner1') -<select name="nestchoice"> -<option value="outer1">Outer 1</option> -<optgroup label="Group "1""> -<option value="inner1" selected="selected">Inner 1</option> -<option value="inner2">Inner 2</option> -</optgroup> -</select> - -# NullBooleanSelect Widget #################################################### - ->>> w = NullBooleanSelect() ->>> print w.render('is_cool', True) -<select name="is_cool"> -<option value="1">Unknown</option> -<option value="2" selected="selected">Yes</option> -<option value="3">No</option> -</select> ->>> print w.render('is_cool', False) -<select name="is_cool"> -<option value="1">Unknown</option> -<option value="2">Yes</option> -<option value="3" selected="selected">No</option> -</select> ->>> print w.render('is_cool', None) -<select name="is_cool"> -<option value="1" selected="selected">Unknown</option> -<option value="2">Yes</option> -<option value="3">No</option> -</select> ->>> print w.render('is_cool', '2') -<select name="is_cool"> -<option value="1">Unknown</option> -<option value="2" selected="selected">Yes</option> -<option value="3">No</option> -</select> ->>> print w.render('is_cool', '3') -<select name="is_cool"> -<option value="1">Unknown</option> -<option value="2">Yes</option> -<option value="3" selected="selected">No</option> -</select> ->>> w._has_changed(False, None) -True ->>> w._has_changed(None, False) -True ->>> w._has_changed(None, None) -False ->>> w._has_changed(False, False) -False ->>> w._has_changed(True, False) -True ->>> w._has_changed(True, None) -True ->>> w._has_changed(True, True) -False - -""" + \ -r""" # [This concatenation is to keep the string below the jython's 32K limit]. -# SelectMultiple Widget ####################################################### - ->>> w = SelectMultiple() ->>> print w.render('beatles', ['J'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<select multiple="multiple" name="beatles"> -<option value="J" selected="selected">John</option> -<option value="P">Paul</option> -<option value="G">George</option> -<option value="R">Ringo</option> -</select> ->>> print w.render('beatles', ['J', 'P'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<select multiple="multiple" name="beatles"> -<option value="J" selected="selected">John</option> -<option value="P" selected="selected">Paul</option> -<option value="G">George</option> -<option value="R">Ringo</option> -</select> ->>> print w.render('beatles', ['J', 'P', 'R'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<select multiple="multiple" name="beatles"> -<option value="J" selected="selected">John</option> -<option value="P" selected="selected">Paul</option> -<option value="G">George</option> -<option value="R" selected="selected">Ringo</option> -</select> - -If the value is None, none of the options are selected: ->>> print w.render('beatles', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<select multiple="multiple" name="beatles"> -<option value="J">John</option> -<option value="P">Paul</option> -<option value="G">George</option> -<option value="R">Ringo</option> -</select> - -If the value corresponds to a label (but not to an option value), none of the options are selected: ->>> print w.render('beatles', ['John'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<select multiple="multiple" name="beatles"> -<option value="J">John</option> -<option value="P">Paul</option> -<option value="G">George</option> -<option value="R">Ringo</option> -</select> - -If multiple values are given, but some of them are not valid, the valid ones are selected: ->>> print w.render('beatles', ['J', 'G', 'foo'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<select multiple="multiple" name="beatles"> -<option value="J" selected="selected">John</option> -<option value="P">Paul</option> -<option value="G" selected="selected">George</option> -<option value="R">Ringo</option> -</select> - -The value is compared to its str(): ->>> print w.render('nums', [2], choices=[('1', '1'), ('2', '2'), ('3', '3')]) -<select multiple="multiple" name="nums"> -<option value="1">1</option> -<option value="2" selected="selected">2</option> -<option value="3">3</option> -</select> ->>> print w.render('nums', ['2'], choices=[(1, 1), (2, 2), (3, 3)]) -<select multiple="multiple" name="nums"> -<option value="1">1</option> -<option value="2" selected="selected">2</option> -<option value="3">3</option> -</select> ->>> print w.render('nums', [2], choices=[(1, 1), (2, 2), (3, 3)]) -<select multiple="multiple" name="nums"> -<option value="1">1</option> -<option value="2" selected="selected">2</option> -<option value="3">3</option> -</select> - -The 'choices' argument can be any iterable: ->>> def get_choices(): -... for i in range(5): -... yield (i, i) ->>> print w.render('nums', [2], choices=get_choices()) -<select multiple="multiple" name="nums"> -<option value="0">0</option> -<option value="1">1</option> -<option value="2" selected="selected">2</option> -<option value="3">3</option> -<option value="4">4</option> -</select> - -You can also pass 'choices' to the constructor: ->>> w = SelectMultiple(choices=[(1, 1), (2, 2), (3, 3)]) ->>> print w.render('nums', [2]) -<select multiple="multiple" name="nums"> -<option value="1">1</option> -<option value="2" selected="selected">2</option> -<option value="3">3</option> -</select> - -If 'choices' is passed to both the constructor and render(), then they'll both be in the output: ->>> print w.render('nums', [2], choices=[(4, 4), (5, 5)]) -<select multiple="multiple" name="nums"> -<option value="1">1</option> -<option value="2" selected="selected">2</option> -<option value="3">3</option> -<option value="4">4</option> -<option value="5">5</option> -</select> - -# Choices are escaped correctly ->>> print w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you > me')))) -<select multiple="multiple" name="escape"> -<option value="1">1</option> -<option value="2">2</option> -<option value="3">3</option> -<option value="bad">you & me</option> -<option value="good">you > me</option> -</select> - -# Unicode choices are correctly rendered as HTML ->>> w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]) -u'<select multiple="multiple" name="nums">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected="selected">\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</option>\n<option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>\n</select>' - -# Test the usage of _has_changed ->>> w._has_changed(None, None) -False ->>> w._has_changed([], None) -False ->>> w._has_changed(None, [u'1']) -True ->>> w._has_changed([1, 2], [u'1', u'2']) -False ->>> w._has_changed([1, 2], [u'1']) -True ->>> w._has_changed([1, 2], [u'1', u'3']) -True - -# Choices can be nested one level in order to create HTML optgroups: ->>> w.choices = (('outer1', 'Outer 1'), ('Group "1"', (('inner1', 'Inner 1'), ('inner2', 'Inner 2')))) ->>> print w.render('nestchoice', None) -<select multiple="multiple" name="nestchoice"> -<option value="outer1">Outer 1</option> -<optgroup label="Group "1""> -<option value="inner1">Inner 1</option> -<option value="inner2">Inner 2</option> -</optgroup> -</select> - ->>> print w.render('nestchoice', ['outer1']) -<select multiple="multiple" name="nestchoice"> -<option value="outer1" selected="selected">Outer 1</option> -<optgroup label="Group "1""> -<option value="inner1">Inner 1</option> -<option value="inner2">Inner 2</option> -</optgroup> -</select> - ->>> print w.render('nestchoice', ['inner1']) -<select multiple="multiple" name="nestchoice"> -<option value="outer1">Outer 1</option> -<optgroup label="Group "1""> -<option value="inner1" selected="selected">Inner 1</option> -<option value="inner2">Inner 2</option> -</optgroup> -</select> - ->>> print w.render('nestchoice', ['outer1', 'inner2']) -<select multiple="multiple" name="nestchoice"> -<option value="outer1" selected="selected">Outer 1</option> -<optgroup label="Group "1""> -<option value="inner1">Inner 1</option> -<option value="inner2" selected="selected">Inner 2</option> -</optgroup> -</select> - -# RadioSelect Widget ########################################################## - ->>> w = RadioSelect() ->>> print w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<ul> -<li><label><input checked="checked" type="radio" name="beatle" value="J" /> John</label></li> -<li><label><input type="radio" name="beatle" value="P" /> Paul</label></li> -<li><label><input type="radio" name="beatle" value="G" /> George</label></li> -<li><label><input type="radio" name="beatle" value="R" /> Ringo</label></li> -</ul> - -If the value is None, none of the options are checked: ->>> print w.render('beatle', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<ul> -<li><label><input type="radio" name="beatle" value="J" /> John</label></li> -<li><label><input type="radio" name="beatle" value="P" /> Paul</label></li> -<li><label><input type="radio" name="beatle" value="G" /> George</label></li> -<li><label><input type="radio" name="beatle" value="R" /> Ringo</label></li> -</ul> - -If the value corresponds to a label (but not to an option value), none of the options are checked: ->>> print w.render('beatle', 'John', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<ul> -<li><label><input type="radio" name="beatle" value="J" /> John</label></li> -<li><label><input type="radio" name="beatle" value="P" /> Paul</label></li> -<li><label><input type="radio" name="beatle" value="G" /> George</label></li> -<li><label><input type="radio" name="beatle" value="R" /> Ringo</label></li> -</ul> - -The value is compared to its str(): ->>> print w.render('num', 2, choices=[('1', '1'), ('2', '2'), ('3', '3')]) -<ul> -<li><label><input type="radio" name="num" value="1" /> 1</label></li> -<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> -<li><label><input type="radio" name="num" value="3" /> 3</label></li> -</ul> ->>> print w.render('num', '2', choices=[(1, 1), (2, 2), (3, 3)]) -<ul> -<li><label><input type="radio" name="num" value="1" /> 1</label></li> -<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> -<li><label><input type="radio" name="num" value="3" /> 3</label></li> -</ul> ->>> print w.render('num', 2, choices=[(1, 1), (2, 2), (3, 3)]) -<ul> -<li><label><input type="radio" name="num" value="1" /> 1</label></li> -<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> -<li><label><input type="radio" name="num" value="3" /> 3</label></li> -</ul> - -The 'choices' argument can be any iterable: ->>> def get_choices(): -... for i in range(5): -... yield (i, i) ->>> print w.render('num', 2, choices=get_choices()) -<ul> -<li><label><input type="radio" name="num" value="0" /> 0</label></li> -<li><label><input type="radio" name="num" value="1" /> 1</label></li> -<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> -<li><label><input type="radio" name="num" value="3" /> 3</label></li> -<li><label><input type="radio" name="num" value="4" /> 4</label></li> -</ul> - -You can also pass 'choices' to the constructor: ->>> w = RadioSelect(choices=[(1, 1), (2, 2), (3, 3)]) ->>> print w.render('num', 2) -<ul> -<li><label><input type="radio" name="num" value="1" /> 1</label></li> -<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> -<li><label><input type="radio" name="num" value="3" /> 3</label></li> -</ul> - -If 'choices' is passed to both the constructor and render(), then they'll both be in the output: ->>> print w.render('num', 2, choices=[(4, 4), (5, 5)]) -<ul> -<li><label><input type="radio" name="num" value="1" /> 1</label></li> -<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li> -<li><label><input type="radio" name="num" value="3" /> 3</label></li> -<li><label><input type="radio" name="num" value="4" /> 4</label></li> -<li><label><input type="radio" name="num" value="5" /> 5</label></li> -</ul> - -RadioSelect uses a RadioFieldRenderer to render the individual radio inputs. -You can manipulate that object directly to customize the way the RadioSelect -is rendered. ->>> w = RadioSelect() ->>> r = w.get_renderer('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) ->>> for inp in r: -... print inp -<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label> -<label><input type="radio" name="beatle" value="P" /> Paul</label> -<label><input type="radio" name="beatle" value="G" /> George</label> -<label><input type="radio" name="beatle" value="R" /> Ringo</label> ->>> for inp in r: -... print '%s<br />' % inp -<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label><br /> -<label><input type="radio" name="beatle" value="P" /> Paul</label><br /> -<label><input type="radio" name="beatle" value="G" /> George</label><br /> -<label><input type="radio" name="beatle" value="R" /> Ringo</label><br /> ->>> for inp in r: -... print '<p>%s %s</p>' % (inp.tag(), inp.choice_label) -<p><input checked="checked" type="radio" name="beatle" value="J" /> John</p> -<p><input type="radio" name="beatle" value="P" /> Paul</p> -<p><input type="radio" name="beatle" value="G" /> George</p> -<p><input type="radio" name="beatle" value="R" /> Ringo</p> ->>> for inp in r: -... print '%s %s %s %s %s' % (inp.name, inp.value, inp.choice_value, inp.choice_label, inp.is_checked()) -beatle J J John True -beatle J P Paul False -beatle J G George False -beatle J R Ringo False - -You can create your own custom renderers for RadioSelect to use. ->>> class MyRenderer(RadioFieldRenderer): -... def render(self): -... return u'<br />\n'.join([unicode(choice) for choice in self]) ->>> w = RadioSelect(renderer=MyRenderer) ->>> print w.render('beatle', 'G', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<label><input type="radio" name="beatle" value="J" /> John</label><br /> -<label><input type="radio" name="beatle" value="P" /> Paul</label><br /> -<label><input checked="checked" type="radio" name="beatle" value="G" /> George</label><br /> -<label><input type="radio" name="beatle" value="R" /> Ringo</label> - -Or you can use custom RadioSelect fields that use your custom renderer. ->>> class CustomRadioSelect(RadioSelect): -... renderer = MyRenderer ->>> w = CustomRadioSelect() ->>> print w.render('beatle', 'G', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<label><input type="radio" name="beatle" value="J" /> John</label><br /> -<label><input type="radio" name="beatle" value="P" /> Paul</label><br /> -<label><input checked="checked" type="radio" name="beatle" value="G" /> George</label><br /> -<label><input type="radio" name="beatle" value="R" /> Ringo</label> - -A RadioFieldRenderer object also allows index access to individual RadioInput -objects. ->>> w = RadioSelect() ->>> r = w.get_renderer('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) ->>> print r[1] -<label><input type="radio" name="beatle" value="P" /> Paul</label> ->>> print r[0] -<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label> ->>> r[0].is_checked() -True ->>> r[1].is_checked() -False ->>> r[1].name, r[1].value, r[1].choice_value, r[1].choice_label -('beatle', u'J', u'P', u'Paul') ->>> r[10] # doctest: +IGNORE_EXCEPTION_DETAIL -Traceback (most recent call last): -... -IndexError: list index out of range - -# Choices are escaped correctly ->>> w = RadioSelect() ->>> print w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you > me')))) -<ul> -<li><label><input type="radio" name="escape" value="bad" /> you & me</label></li> -<li><label><input type="radio" name="escape" value="good" /> you > me</label></li> -</ul> - -# Unicode choices are correctly rendered as HTML ->>> w = RadioSelect() ->>> unicode(w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')])) -u'<ul>\n<li><label><input checked="checked" type="radio" name="email" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" /> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label></li>\n<li><label><input type="radio" name="email" value="\u0107\u017e\u0161\u0111" /> abc\u0107\u017e\u0161\u0111</label></li>\n</ul>' - -# Attributes provided at instantiation are passed to the constituent inputs ->>> w = RadioSelect(attrs={'id':'foo'}) ->>> print w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<ul> -<li><label for="foo_0"><input checked="checked" type="radio" id="foo_0" value="J" name="beatle" /> John</label></li> -<li><label for="foo_1"><input type="radio" id="foo_1" value="P" name="beatle" /> Paul</label></li> -<li><label for="foo_2"><input type="radio" id="foo_2" value="G" name="beatle" /> George</label></li> -<li><label for="foo_3"><input type="radio" id="foo_3" value="R" name="beatle" /> Ringo</label></li> -</ul> - -# Attributes provided at render-time are passed to the constituent inputs ->>> w = RadioSelect() ->>> print w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')), attrs={'id':'bar'}) -<ul> -<li><label for="bar_0"><input checked="checked" type="radio" id="bar_0" value="J" name="beatle" /> John</label></li> -<li><label for="bar_1"><input type="radio" id="bar_1" value="P" name="beatle" /> Paul</label></li> -<li><label for="bar_2"><input type="radio" id="bar_2" value="G" name="beatle" /> George</label></li> -<li><label for="bar_3"><input type="radio" id="bar_3" value="R" name="beatle" /> Ringo</label></li> -</ul> - -# CheckboxSelectMultiple Widget ############################################### - ->>> w = CheckboxSelectMultiple() ->>> print w.render('beatles', ['J'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<ul> -<li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li> -<li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> -<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> -<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> -</ul> ->>> print w.render('beatles', ['J', 'P'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<ul> -<li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li> -<li><label><input checked="checked" type="checkbox" name="beatles" value="P" /> Paul</label></li> -<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> -<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> -</ul> ->>> print w.render('beatles', ['J', 'P', 'R'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<ul> -<li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li> -<li><label><input checked="checked" type="checkbox" name="beatles" value="P" /> Paul</label></li> -<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> -<li><label><input checked="checked" type="checkbox" name="beatles" value="R" /> Ringo</label></li> -</ul> - -If the value is None, none of the options are selected: ->>> print w.render('beatles', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<ul> -<li><label><input type="checkbox" name="beatles" value="J" /> John</label></li> -<li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> -<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> -<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> -</ul> - -If the value corresponds to a label (but not to an option value), none of the options are selected: ->>> print w.render('beatles', ['John'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<ul> -<li><label><input type="checkbox" name="beatles" value="J" /> John</label></li> -<li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> -<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li> -<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> -</ul> - -If multiple values are given, but some of them are not valid, the valid ones are selected: ->>> print w.render('beatles', ['J', 'G', 'foo'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -<ul> -<li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li> -<li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li> -<li><label><input checked="checked" type="checkbox" name="beatles" value="G" /> George</label></li> -<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li> -</ul> - -The value is compared to its str(): ->>> print w.render('nums', [2], choices=[('1', '1'), ('2', '2'), ('3', '3')]) -<ul> -<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> -<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> -<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> -</ul> ->>> print w.render('nums', ['2'], choices=[(1, 1), (2, 2), (3, 3)]) -<ul> -<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> -<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> -<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> -</ul> ->>> print w.render('nums', [2], choices=[(1, 1), (2, 2), (3, 3)]) -<ul> -<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> -<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> -<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> -</ul> - -The 'choices' argument can be any iterable: ->>> def get_choices(): -... for i in range(5): -... yield (i, i) ->>> print w.render('nums', [2], choices=get_choices()) -<ul> -<li><label><input type="checkbox" name="nums" value="0" /> 0</label></li> -<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> -<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> -<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> -<li><label><input type="checkbox" name="nums" value="4" /> 4</label></li> -</ul> - -You can also pass 'choices' to the constructor: ->>> w = CheckboxSelectMultiple(choices=[(1, 1), (2, 2), (3, 3)]) ->>> print w.render('nums', [2]) -<ul> -<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> -<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> -<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> -</ul> - -If 'choices' is passed to both the constructor and render(), then they'll both be in the output: ->>> print w.render('nums', [2], choices=[(4, 4), (5, 5)]) -<ul> -<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li> -<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li> -<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li> -<li><label><input type="checkbox" name="nums" value="4" /> 4</label></li> -<li><label><input type="checkbox" name="nums" value="5" /> 5</label></li> -</ul> - -# Choices are escaped correctly ->>> print w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you > me')))) -<ul> -<li><label><input type="checkbox" name="escape" value="1" /> 1</label></li> -<li><label><input type="checkbox" name="escape" value="2" /> 2</label></li> -<li><label><input type="checkbox" name="escape" value="3" /> 3</label></li> -<li><label><input type="checkbox" name="escape" value="bad" /> you & me</label></li> -<li><label><input type="checkbox" name="escape" value="good" /> you > me</label></li> -</ul> - -# Test the usage of _has_changed ->>> w._has_changed(None, None) -False ->>> w._has_changed([], None) -False ->>> w._has_changed(None, [u'1']) -True ->>> w._has_changed([1, 2], [u'1', u'2']) -False ->>> w._has_changed([1, 2], [u'1']) -True ->>> w._has_changed([1, 2], [u'1', u'3']) -True - -# Unicode choices are correctly rendered as HTML ->>> w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]) -u'<ul>\n<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li>\n<li><label><input type="checkbox" name="nums" value="2" /> 2</label></li>\n<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li>\n<li><label><input checked="checked" type="checkbox" name="nums" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" /> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label></li>\n<li><label><input type="checkbox" name="nums" value="\u0107\u017e\u0161\u0111" /> abc\u0107\u017e\u0161\u0111</label></li>\n</ul>' - -# Each input gets a separate ID ->>> print CheckboxSelectMultiple().render('letters', list('ac'), choices=zip(list('abc'), list('ABC')), attrs={'id': 'abc'}) -<ul> -<li><label for="abc_0"><input checked="checked" type="checkbox" name="letters" value="a" id="abc_0" /> A</label></li> -<li><label for="abc_1"><input type="checkbox" name="letters" value="b" id="abc_1" /> B</label></li> -<li><label for="abc_2"><input checked="checked" type="checkbox" name="letters" value="c" id="abc_2" /> C</label></li> -</ul> - -# MultiWidget ################################################################# - ->>> class MyMultiWidget(MultiWidget): -... def decompress(self, value): -... if value: -... return value.split('__') -... return ['', ''] -... def format_output(self, rendered_widgets): -... return u'<br />'.join(rendered_widgets) ->>> w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'}))) ->>> w.render('name', ['john', 'lennon']) -u'<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />' ->>> w.render('name', 'john__lennon') -u'<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />' ->>> w.render('name', 'john__lennon', attrs={'id':'foo'}) -u'<input id="foo_0" type="text" class="big" value="john" name="name_0" /><br /><input id="foo_1" type="text" class="small" value="lennon" name="name_1" />' ->>> w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'})), attrs={'id': 'bar'}) ->>> w.render('name', ['john', 'lennon']) -u'<input id="bar_0" type="text" class="big" value="john" name="name_0" /><br /><input id="bar_1" type="text" class="small" value="lennon" name="name_1" />' - ->>> w = MyMultiWidget(widgets=(TextInput(), TextInput())) - -# test with no initial data ->>> w._has_changed(None, [u'john', u'lennon']) -True - -# test when the data is the same as initial ->>> w._has_changed(u'john__lennon', [u'john', u'lennon']) -False - -# test when the first widget's data has changed ->>> w._has_changed(u'john__lennon', [u'alfred', u'lennon']) -True - -# test when the last widget's data has changed. this ensures that it is not -# short circuiting while testing the widgets. ->>> w._has_changed(u'john__lennon', [u'john', u'denver']) -True - -# SplitDateTimeWidget ######################################################### - ->>> w = SplitDateTimeWidget() ->>> w.render('date', '') -u'<input type="text" name="date_0" /><input type="text" name="date_1" />' ->>> w.render('date', None) -u'<input type="text" name="date_0" /><input type="text" name="date_1" />' ->>> w.render('date', datetime.datetime(2006, 1, 10, 7, 30)) -u'<input type="text" name="date_0" value="2006-01-10" /><input type="text" name="date_1" value="07:30:00" />' ->>> w.render('date', [datetime.date(2006, 1, 10), datetime.time(7, 30)]) -u'<input type="text" name="date_0" value="2006-01-10" /><input type="text" name="date_1" value="07:30:00" />' - -You can also pass 'attrs' to the constructor. In this case, the attrs will be -included on both widgets. ->>> w = SplitDateTimeWidget(attrs={'class': 'pretty'}) ->>> w.render('date', datetime.datetime(2006, 1, 10, 7, 30)) -u'<input type="text" class="pretty" value="2006-01-10" name="date_0" /><input type="text" class="pretty" value="07:30:00" name="date_1" />' - -Use 'date_format' and 'time_format' to change the way a value is displayed. ->>> w = SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M') ->>> w.render('date', datetime.datetime(2006, 1, 10, 7, 30)) -u'<input type="text" name="date_0" value="10/01/2006" /><input type="text" name="date_1" value="07:30" />' - ->>> w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'2008-05-06', u'12:40:00']) -True ->>> w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'06/05/2008', u'12:40']) -False ->>> w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'06/05/2008', u'12:41']) -True ->>> activate('de-at') ->>> settings.USE_L10N = True ->>> w._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), [u'06.05.2008', u'12:41']) -True ->>> deactivate() ->>> settings.USE_L10N = False - - -# DateTimeInput ############################################################### - ->>> w = DateTimeInput() ->>> w.render('date', None) -u'<input type="text" name="date" />' ->>> d = datetime.datetime(2007, 9, 17, 12, 51, 34, 482548) ->>> print d -2007-09-17 12:51:34.482548 - -The microseconds are trimmed on display, by default. ->>> w.render('date', d) -u'<input type="text" name="date" value="2007-09-17 12:51:34" />' ->>> w.render('date', datetime.datetime(2007, 9, 17, 12, 51, 34)) -u'<input type="text" name="date" value="2007-09-17 12:51:34" />' ->>> w.render('date', datetime.datetime(2007, 9, 17, 12, 51)) -u'<input type="text" name="date" value="2007-09-17 12:51:00" />' ->>> activate('de-at') ->>> settings.USE_L10N = True ->>> w.is_localized = True ->>> w.render('date', d) -u'<input type="text" name="date" value="17.09.2007 12:51:34" />' ->>> deactivate() ->>> settings.USE_L10N = False - -Use 'format' to change the way a value is displayed. ->>> w = DateTimeInput(format='%d/%m/%Y %H:%M') ->>> w.render('date', d) -u'<input type="text" name="date" value="17/09/2007 12:51" />' ->>> w._has_changed(d, '17/09/2007 12:51') -False - -Make sure a custom format works with _has_changed. The hidden input will use -format.localize_input to display the initial value. ->>> data = datetime.datetime(2010, 3, 6, 12, 0, 0) ->>> custom_format = '%d.%m.%Y %H:%M' ->>> w = DateTimeInput(format=custom_format) ->>> w._has_changed(formats.localize_input(data), data.strftime(custom_format)) -False - - -# DateInput ################################################################### - ->>> w = DateInput() ->>> w.render('date', None) -u'<input type="text" name="date" />' ->>> d = datetime.date(2007, 9, 17) ->>> print d -2007-09-17 - ->>> w.render('date', d) -u'<input type="text" name="date" value="2007-09-17" />' ->>> w.render('date', datetime.date(2007, 9, 17)) -u'<input type="text" name="date" value="2007-09-17" />' - -We should be able to initialize from a unicode value. ->>> w.render('date', u'2007-09-17') -u'<input type="text" name="date" value="2007-09-17" />' - ->>> activate('de-at') ->>> settings.USE_L10N = True ->>> w.is_localized = True ->>> w.render('date', d) -u'<input type="text" name="date" value="17.09.2007" />' ->>> deactivate() ->>> settings.USE_L10N = False - -Use 'format' to change the way a value is displayed. ->>> w = DateInput(format='%d/%m/%Y') ->>> w.render('date', d) -u'<input type="text" name="date" value="17/09/2007" />' ->>> w._has_changed(d, '17/09/2007') -False - -Make sure a custom format works with _has_changed. The hidden input will use -format.localize_input to display the initial value. ->>> data = datetime.date(2010, 3, 6) ->>> custom_format = '%d.%m.%Y' ->>> w = DateInput(format=custom_format) ->>> w._has_changed(formats.localize_input(data), data.strftime(custom_format)) -False - - -# TimeInput ################################################################### - ->>> w = TimeInput() ->>> w.render('time', None) -u'<input type="text" name="time" />' ->>> t = datetime.time(12, 51, 34, 482548) ->>> print t -12:51:34.482548 - -The microseconds are trimmed on display, by default. ->>> w.render('time', t) -u'<input type="text" name="time" value="12:51:34" />' ->>> w.render('time', datetime.time(12, 51, 34)) -u'<input type="text" name="time" value="12:51:34" />' ->>> w.render('time', datetime.time(12, 51)) -u'<input type="text" name="time" value="12:51:00" />' - -We should be able to initialize from a unicode value. ->>> w.render('time', u'13:12:11') -u'<input type="text" name="time" value="13:12:11" />' - ->>> activate('de-at') ->>> settings.USE_L10N = True ->>> w.is_localized = True ->>> w.render('date', d) -u'<input type="text" name="date" value="17.09.2007" />' ->>> deactivate() ->>> settings.USE_L10N = False - -Use 'format' to change the way a value is displayed. ->>> w = TimeInput(format='%H:%M') ->>> w.render('time', t) -u'<input type="text" name="time" value="12:51" />' ->>> w._has_changed(t, '12:51') -False - -Make sure a custom format works with _has_changed. The hidden input will use -format.localize_input to display the initial value. ->>> data = datetime.time(13, 0) ->>> custom_format = '%I:%M %p' ->>> w = TimeInput(format=custom_format) ->>> w._has_changed(formats.localize_input(data), data.strftime(custom_format)) -False - - -# SplitHiddenDateTimeWidget ################################################### - ->>> from django.forms.widgets import SplitHiddenDateTimeWidget - ->>> w = SplitHiddenDateTimeWidget() ->>> w.render('date', '') -u'<input type="hidden" name="date_0" /><input type="hidden" name="date_1" />' ->>> d = datetime.datetime(2007, 9, 17, 12, 51, 34, 482548) ->>> print d -2007-09-17 12:51:34.482548 ->>> w.render('date', d) -u'<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:34" />' ->>> w.render('date', datetime.datetime(2007, 9, 17, 12, 51, 34)) -u'<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:34" />' ->>> w.render('date', datetime.datetime(2007, 9, 17, 12, 51)) -u'<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:00" />' ->>> activate('de-at') ->>> settings.USE_L10N = True ->>> w.is_localized = True ->>> w.render('date', datetime.datetime(2007, 9, 17, 12, 51)) -u'<input type="hidden" name="date_0" value="17.09.2007" /><input type="hidden" name="date_1" value="12:51:00" />' ->>> deactivate() ->>> settings.USE_L10N = False - -""" - -from django import forms -from django.utils import copycompat as copy -from django.utils.unittest import TestCase -from django.core.files.uploadedfile import SimpleUploadedFile - - -class SelectAndTextWidget(forms.MultiWidget): - """ - MultiWidget subclass - """ - def __init__(self, choices=[]): - widgets = [ - forms.RadioSelect(choices=choices), - forms.TextInput - ] - super(SelectAndTextWidget, self).__init__(widgets) - - def _set_choices(self, choices): - """ - When choices are set for this widget, we want to pass those along to the Select widget - """ - self.widgets[0].choices = choices - def _get_choices(self): - """ - The choices for this widget are the Select widget's choices - """ - return self.widgets[0].choices - choices = property(_get_choices, _set_choices) - - -class WidgetTests(TestCase): - - def test_12048(self): - # See ticket #12048. - w1 = SelectAndTextWidget(choices=[1,2,3]) - w2 = copy.deepcopy(w1) - w2.choices = [4,5,6] - # w2 ought to be independent of w1, since MultiWidget ought - # to make a copy of its sub-widgets when it is copied. - self.assertEqual(w1.choices, [1,2,3]) - - def test_13390(self): - # See ticket #13390 - class SplitDateForm(forms.Form): - field = forms.DateTimeField(widget=forms.SplitDateTimeWidget, required=False) - - form = SplitDateForm({'field': ''}) - self.assertTrue(form.is_valid()) - form = SplitDateForm({'field': ['', '']}) - self.assertTrue(form.is_valid()) - - class SplitDateRequiredForm(forms.Form): - field = forms.DateTimeField(widget=forms.SplitDateTimeWidget, required=True) - - form = SplitDateRequiredForm({'field': ''}) - self.assertFalse(form.is_valid()) - form = SplitDateRequiredForm({'field': ['', '']}) - self.assertFalse(form.is_valid()) - - -class FakeFieldFile(object): - """ - Quacks like a FieldFile (has a .url and unicode representation), but - doesn't require us to care about storages etc. - - """ - url = 'something' - - def __unicode__(self): - return self.url - -class ClearableFileInputTests(TestCase): - def test_clear_input_renders(self): - """ - A ClearableFileInput with is_required False and rendered with - an initial value that is a file renders a clear checkbox. - - """ - widget = forms.ClearableFileInput() - widget.is_required = False - self.assertEqual(widget.render('myfile', FakeFieldFile()), - u'Currently: <a target="_blank" href="something">something</a> <input type="checkbox" name="myfile-clear" id="myfile-clear_id" /> <label for="myfile-clear_id">Clear</label><br />Change: <input type="file" name="myfile" />') - - def test_clear_input_renders_only_if_not_required(self): - """ - A ClearableFileInput with is_required=False does not render a clear - checkbox. - - """ - widget = forms.ClearableFileInput() - widget.is_required = True - self.assertEqual(widget.render('myfile', FakeFieldFile()), - u'Currently: <a target="_blank" href="something">something</a> <br />Change: <input type="file" name="myfile" />') - - def test_clear_input_renders_only_if_initial(self): - """ - A ClearableFileInput instantiated with no initial value does not render - a clear checkbox. - - """ - widget = forms.ClearableFileInput() - widget.is_required = False - self.assertEqual(widget.render('myfile', None), - u'<input type="file" name="myfile" />') - - def test_clear_input_checked_returns_false(self): - """ - ClearableFileInput.value_from_datadict returns False if the clear - checkbox is checked, if not required. - - """ - widget = forms.ClearableFileInput() - widget.is_required = False - self.assertEqual(widget.value_from_datadict( - data={'myfile-clear': True}, - files={}, - name='myfile'), False) - - def test_clear_input_checked_returns_false_only_if_not_required(self): - """ - ClearableFileInput.value_from_datadict never returns False if the field - is required. - - """ - widget = forms.ClearableFileInput() - widget.is_required = True - f = SimpleUploadedFile('something.txt', 'content') - self.assertEqual(widget.value_from_datadict( - data={'myfile-clear': True}, - files={'myfile': f}, - name='myfile'), f)