summaryrefslogtreecommitdiff
path: root/tests/forms_tests
diff options
context:
space:
mode:
authorFlorian Apolloner <florian@apolloner.eu>2013-02-26 13:19:18 +0100
committerFlorian Apolloner <florian@apolloner.eu>2013-02-26 14:36:57 +0100
commit33836cf88dd08ebd66d19ad7f732b12f089abd27 (patch)
tree6a812006f1f3a1f3dc7e51e4d0417ca8aadc86ef /tests/forms_tests
parent737a5d71f084ac804519c0bac33e2498d712bbb7 (diff)
Renamed some tests and removed references to modeltests/regressiontests.
Diffstat (limited to 'tests/forms_tests')
-rw-r--r--tests/forms_tests/__init__.py0
-rw-r--r--tests/forms_tests/models.py90
-rw-r--r--tests/forms_tests/templates/forms/article_form.html8
-rw-r--r--tests/forms_tests/tests/__init__.py21
-rw-r--r--tests/forms_tests/tests/error_messages.py263
-rw-r--r--tests/forms_tests/tests/extra.py807
-rw-r--r--tests/forms_tests/tests/fields.py1190
-rw-r--r--tests/forms_tests/tests/filepath_test_files/.dot-file0
-rw-r--r--tests/forms_tests/tests/filepath_test_files/directory/.keep0
-rw-r--r--tests/forms_tests/tests/filepath_test_files/fake-image.jpg0
-rw-r--r--tests/forms_tests/tests/filepath_test_files/real-text-file.txt0
-rw-r--r--tests/forms_tests/tests/forms.py1799
-rw-r--r--tests/forms_tests/tests/formsets.py1055
-rw-r--r--tests/forms_tests/tests/input_formats.py861
-rw-r--r--tests/forms_tests/tests/media.py907
-rw-r--r--tests/forms_tests/tests/models.py218
-rw-r--r--tests/forms_tests/tests/regressions.py150
-rw-r--r--tests/forms_tests/tests/util.py67
-rw-r--r--tests/forms_tests/tests/validators.py16
-rw-r--r--tests/forms_tests/tests/widgets.py1124
-rw-r--r--tests/forms_tests/urls.py9
-rw-r--r--tests/forms_tests/views.py8
22 files changed, 8593 insertions, 0 deletions
diff --git a/tests/forms_tests/__init__.py b/tests/forms_tests/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/tests/forms_tests/__init__.py
diff --git a/tests/forms_tests/models.py b/tests/forms_tests/models.py
new file mode 100644
index 0000000000..bec31d12d7
--- /dev/null
+++ b/tests/forms_tests/models.py
@@ -0,0 +1,90 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+import os
+import datetime
+import tempfile
+
+from django.core.files.storage import FileSystemStorage
+from django.db import models
+from django.utils.encoding import python_2_unicode_compatible
+
+
+temp_storage_location = tempfile.mkdtemp(dir=os.environ['DJANGO_TEST_TEMP_DIR'])
+temp_storage = FileSystemStorage(location=temp_storage_location)
+
+
+class BoundaryModel(models.Model):
+ positive_integer = models.PositiveIntegerField(null=True, blank=True)
+
+
+callable_default_value = 0
+def callable_default():
+ global callable_default_value
+ callable_default_value = callable_default_value + 1
+ return callable_default_value
+
+
+class Defaults(models.Model):
+ name = models.CharField(max_length=255, default='class default value')
+ def_date = models.DateField(default = datetime.date(1980, 1, 1))
+ value = models.IntegerField(default=42)
+ callable_default = models.IntegerField(default=callable_default)
+
+
+class ChoiceModel(models.Model):
+ """For ModelChoiceField and ModelMultipleChoiceField tests."""
+ name = models.CharField(max_length=10)
+
+
+@python_2_unicode_compatible
+class ChoiceOptionModel(models.Model):
+ """Destination for ChoiceFieldModel's ForeignKey.
+ Can't reuse ChoiceModel because error_message tests require that it have no instances."""
+ name = models.CharField(max_length=10)
+
+ class Meta:
+ ordering = ('name',)
+
+ def __str__(self):
+ return 'ChoiceOption %d' % self.pk
+
+
+class ChoiceFieldModel(models.Model):
+ """Model with ForeignKey to another model, for testing ModelForm
+ generation with ModelChoiceField."""
+ choice = models.ForeignKey(ChoiceOptionModel, blank=False,
+ default=lambda: ChoiceOptionModel.objects.get(name='default'))
+ choice_int = models.ForeignKey(ChoiceOptionModel, blank=False, related_name='choice_int',
+ default=lambda: 1)
+
+ multi_choice = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='multi_choice',
+ default=lambda: ChoiceOptionModel.objects.filter(name='default'))
+ multi_choice_int = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='multi_choice_int',
+ default=lambda: [1])
+
+class OptionalMultiChoiceModel(models.Model):
+ multi_choice = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='not_relevant',
+ default=lambda: ChoiceOptionModel.objects.filter(name='default'))
+ multi_choice_optional = models.ManyToManyField(ChoiceOptionModel, blank=True, null=True,
+ related_name='not_relevant2')
+
+
+class FileModel(models.Model):
+ file = models.FileField(storage=temp_storage, upload_to='tests')
+
+
+@python_2_unicode_compatible
+class Group(models.Model):
+ name = models.CharField(max_length=10)
+
+ def __str__(self):
+ return '%s' % self.name
+
+
+class Cheese(models.Model):
+ name = models.CharField(max_length=100)
+
+
+class Article(models.Model):
+ content = models.TextField()
diff --git a/tests/forms_tests/templates/forms/article_form.html b/tests/forms_tests/templates/forms/article_form.html
new file mode 100644
index 0000000000..cde85051f6
--- /dev/null
+++ b/tests/forms_tests/templates/forms/article_form.html
@@ -0,0 +1,8 @@
+<html>
+<body>
+ <form method="post" action=".">
+ {{ form.as_p }}<br>
+ <input id="submit" type="submit">
+ </form>
+</body>
+</html>
diff --git a/tests/forms_tests/tests/__init__.py b/tests/forms_tests/tests/__init__.py
new file mode 100644
index 0000000000..6708e54c79
--- /dev/null
+++ b/tests/forms_tests/tests/__init__.py
@@ -0,0 +1,21 @@
+from __future__ import absolute_import
+
+from .error_messages import (FormsErrorMessagesTestCase,
+ ModelChoiceFieldErrorMessagesTestCase)
+from .extra import FormsExtraTestCase, FormsExtraL10NTestCase
+from .fields import FieldsTests
+from .forms import FormsTestCase
+from .formsets import (FormsFormsetTestCase, FormsetAsFooTests,
+ TestIsBoundBehavior, TestEmptyFormSet)
+from .input_formats import (LocalizedTimeTests, CustomTimeInputFormatsTests,
+ SimpleTimeFormatTests, LocalizedDateTests, CustomDateInputFormatsTests,
+ SimpleDateFormatTests, LocalizedDateTimeTests,
+ CustomDateTimeInputFormatsTests, SimpleDateTimeFormatTests)
+from .media import FormsMediaTestCase, StaticFormsMediaTestCase
+from .models import (TestTicket12510, ModelFormCallableModelDefault,
+ FormsModelTestCase, RelatedModelFormTests)
+from .regressions import FormsRegressionsTestCase
+from .util import FormsUtilTestCase
+from .validators import TestFieldWithValidators
+from .widgets import (FormsWidgetTestCase, FormsI18NWidgetsTestCase,
+ WidgetTests, LiveWidgetTests, ClearableFileInputTests)
diff --git a/tests/forms_tests/tests/error_messages.py b/tests/forms_tests/tests/error_messages.py
new file mode 100644
index 0000000000..af047daf64
--- /dev/null
+++ b/tests/forms_tests/tests/error_messages.py
@@ -0,0 +1,263 @@
+# -*- coding: utf-8 -*-
+from __future__ import absolute_import, unicode_literals
+
+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.encoding import python_2_unicode_compatible
+
+
+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 as e:
+ self.assertEqual(e.messages, expected)
+
+class FormsErrorMessagesTestCase(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(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['LENGTH 4, MIN LENGTH 5'], f.clean, '1234')
+ self.assertFormErrors(['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(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['INVALID'], f.clean, 'abc')
+ self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4')
+ self.assertFormErrors(['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(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['INVALID'], f.clean, 'abc')
+ self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4')
+ self.assertFormErrors(['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(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['INVALID'], f.clean, 'abc')
+ self.assertFormErrors(['MIN VALUE IS 5'], f.clean, '4')
+ self.assertFormErrors(['MAX VALUE IS 10'], f.clean, '11')
+
+ f2 = DecimalField(max_digits=4, decimal_places=2, error_messages=e)
+ self.assertFormErrors(['MAX DIGITS IS 4'], f2.clean, '123.45')
+ self.assertFormErrors(['MAX DP IS 2'], f2.clean, '1.234')
+ self.assertFormErrors(['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(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['INVALID'], f.clean, 'abc')
+
+ def test_timefield(self):
+ e = {
+ 'required': 'REQUIRED',
+ 'invalid': 'INVALID',
+ }
+ f = TimeField(error_messages=e)
+ self.assertFormErrors(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['INVALID'], f.clean, 'abc')
+
+ def test_datetimefield(self):
+ e = {
+ 'required': 'REQUIRED',
+ 'invalid': 'INVALID',
+ }
+ f = DateTimeField(error_messages=e)
+ self.assertFormErrors(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['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(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['INVALID'], f.clean, 'abcde')
+ self.assertFormErrors(['LENGTH 4, MIN LENGTH 5'], f.clean, '1234')
+ self.assertFormErrors(['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(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['INVALID'], f.clean, 'abcdefgh')
+ self.assertFormErrors(['LENGTH 7, MIN LENGTH 8'], f.clean, 'a@b.com')
+ self.assertFormErrors(['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(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['INVALID'], f.clean, 'abc')
+ self.assertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', None))
+ self.assertFormErrors(['EMPTY FILE'], f.clean, SimpleUploadedFile('name', ''))
+
+ def test_urlfield(self):
+ e = {
+ 'required': 'REQUIRED',
+ 'invalid': 'INVALID',
+ }
+ f = URLField(error_messages=e)
+ self.assertFormErrors(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['INVALID'], f.clean, 'abc.c')
+
+ def test_booleanfield(self):
+ e = {
+ 'required': 'REQUIRED',
+ }
+ f = BooleanField(error_messages=e)
+ self.assertFormErrors(['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(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['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(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['NOT A LIST'], f.clean, 'b')
+ self.assertFormErrors(['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(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['INVALID DATE', 'INVALID TIME'], f.clean, ['a', 'b'])
+
+ def test_ipaddressfield(self):
+ e = {
+ 'required': 'REQUIRED',
+ 'invalid': 'INVALID IP ADDRESS',
+ }
+ f = IPAddressField(error_messages=e)
+ self.assertFormErrors(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['INVALID IP ADDRESS'], f.clean, '127.0.0')
+
+ def test_generic_ipaddressfield(self):
+ e = {
+ 'required': 'REQUIRED',
+ 'invalid': 'INVALID IP ADDRESS',
+ }
+ f = GenericIPAddressField(error_messages=e)
+ self.assertFormErrors(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['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.")
+
+ @python_2_unicode_compatible
+ class CustomErrorList(util.ErrorList):
+ def __str__(self):
+ return self.as_divs()
+
+ def as_divs(self):
+ if not self: return ''
+ return mark_safe('<div class="error">%s</div>' % ''.join(['<p>%s</p>' % e for e in self]))
+
+ # This form should print errors the default way.
+ form1 = TestForm({'first_name': 'John'})
+ self.assertHTMLEqual(str(form1['last_name'].errors), '<ul class="errorlist"><li>This field is required.</li></ul>')
+ self.assertHTMLEqual(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.assertHTMLEqual(str(form2['last_name'].errors), '<div class="error"><p>This field is required.</p></div>')
+ self.assertHTMLEqual(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 forms_tests.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(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['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(['REQUIRED'], f.clean, '')
+ self.assertFormErrors(['NOT A LIST OF VALUES'], f.clean, '3')
+ self.assertFormErrors(['4 IS INVALID CHOICE'], f.clean, ['4'])
diff --git a/tests/forms_tests/tests/extra.py b/tests/forms_tests/tests/extra.py
new file mode 100644
index 0000000000..359ad442bc
--- /dev/null
+++ b/tests/forms_tests/tests/extra.py
@@ -0,0 +1,807 @@
+# -*- coding: utf-8 -*-
+from __future__ import absolute_import, unicode_literals
+
+import datetime
+
+from django.forms import *
+from django.forms.extras import SelectDateWidget
+from django.forms.util import ErrorList
+from django.test import TestCase
+from django.test.utils import override_settings
+from django.utils import six
+from django.utils import translation
+from django.utils.encoding import force_text, smart_text, python_2_unicode_compatible
+
+from .error_messages import AssertFormErrorsMixin
+
+
+class GetDate(Form):
+ mydate = DateField(widget=SelectDateWidget)
+
+class GetNotRequiredDate(Form):
+ mydate = DateField(widget=SelectDateWidget, required=False)
+
+class GetDateShowHiddenInitial(Form):
+ mydate = DateField(widget=SelectDateWidget, show_hidden_initial=True)
+
+class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
+ ###############
+ # Extra stuff #
+ ###############
+
+ # 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.assertHTMLEqual(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>
+<option value="3">March</option>
+<option value="4">April</option>
+<option value="5">May</option>
+<option value="6">June</option>
+<option value="7">July</option>
+<option value="8">August</option>
+<option value="9">September</option>
+<option value="10">October</option>
+<option value="11">November</option>
+<option value="12">December</option>
+</select>
+
+<select name="mydate_day" id="id_mydate_day">
+<option value="0">---</option>
+<option value="1">1</option>
+<option value="2">2</option>
+<option value="3">3</option>
+<option value="4">4</option>
+<option value="5">5</option>
+<option value="6">6</option>
+<option value="7">7</option>
+<option value="8">8</option>
+<option value="9">9</option>
+<option value="10">10</option>
+<option value="11">11</option>
+<option value="12">12</option>
+<option value="13">13</option>
+<option value="14">14</option>
+<option value="15">15</option>
+<option value="16">16</option>
+<option value="17">17</option>
+<option value="18">18</option>
+<option value="19">19</option>
+<option value="20">20</option>
+<option value="21">21</option>
+<option value="22">22</option>
+<option value="23">23</option>
+<option value="24">24</option>
+<option value="25">25</option>
+<option value="26">26</option>
+<option value="27">27</option>
+<option value="28">28</option>
+<option value="29">29</option>
+<option value="30">30</option>
+<option value="31">31</option>
+</select>
+
+<select name="mydate_year" id="id_mydate_year">
+<option value="0">---</option>
+<option value="2007">2007</option>
+<option value="2008">2008</option>
+<option value="2009">2009</option>
+<option value="2010">2010</option>
+<option value="2011">2011</option>
+<option value="2012">2012</option>
+<option value="2013">2013</option>
+<option value="2014">2014</option>
+<option value="2015">2015</option>
+<option value="2016">2016</option>
+</select>""")
+ self.assertHTMLEqual(w.render('mydate', None), w.render('mydate', ''))
+
+ self.assertHTMLEqual(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>
+<option value="4" selected="selected">April</option>
+<option value="5">May</option>
+<option value="6">June</option>
+<option value="7">July</option>
+<option value="8">August</option>
+<option value="9">September</option>
+<option value="10">October</option>
+<option value="11">November</option>
+<option value="12">December</option>
+</select>
+<select name="mydate_day" id="id_mydate_day">
+<option value="1">1</option>
+<option value="2">2</option>
+<option value="3">3</option>
+<option value="4">4</option>
+<option value="5">5</option>
+<option value="6">6</option>
+<option value="7">7</option>
+<option value="8">8</option>
+<option value="9">9</option>
+<option value="10">10</option>
+<option value="11">11</option>
+<option value="12">12</option>
+<option value="13">13</option>
+<option value="14">14</option>
+<option value="15" selected="selected">15</option>
+<option value="16">16</option>
+<option value="17">17</option>
+<option value="18">18</option>
+<option value="19">19</option>
+<option value="20">20</option>
+<option value="21">21</option>
+<option value="22">22</option>
+<option value="23">23</option>
+<option value="24">24</option>
+<option value="25">25</option>
+<option value="26">26</option>
+<option value="27">27</option>
+<option value="28">28</option>
+<option value="29">29</option>
+<option value="30">30</option>
+<option value="31">31</option>
+</select>
+<select name="mydate_year" id="id_mydate_year">
+<option value="2007">2007</option>
+<option value="2008">2008</option>
+<option value="2009">2009</option>
+<option value="2010" selected="selected">2010</option>
+<option value="2011">2011</option>
+<option value="2012">2012</option>
+<option value="2013">2013</option>
+<option value="2014">2014</option>
+<option value="2015">2015</option>
+<option value="2016">2016</option>
+</select>""")
+
+ # Accepts a datetime or a string:
+ self.assertHTMLEqual(w.render('mydate', datetime.date(2010, 4, 15)), w.render('mydate', '2010-04-15'))
+
+ # Invalid dates still render the failed date:
+ self.assertHTMLEqual(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>
+<option value="4">April</option>
+<option value="5">May</option>
+<option value="6">June</option>
+<option value="7">July</option>
+<option value="8">August</option>
+<option value="9">September</option>
+<option value="10">October</option>
+<option value="11">November</option>
+<option value="12">December</option>
+</select>
+<select name="mydate_day" id="id_mydate_day">
+<option value="1">1</option>
+<option value="2">2</option>
+<option value="3">3</option>
+<option value="4">4</option>
+<option value="5">5</option>
+<option value="6">6</option>
+<option value="7">7</option>
+<option value="8">8</option>
+<option value="9">9</option>
+<option value="10">10</option>
+<option value="11">11</option>
+<option value="12">12</option>
+<option value="13">13</option>
+<option value="14">14</option>
+<option value="15">15</option>
+<option value="16">16</option>
+<option value="17">17</option>
+<option value="18">18</option>
+<option value="19">19</option>
+<option value="20">20</option>
+<option value="21">21</option>
+<option value="22">22</option>
+<option value="23">23</option>
+<option value="24">24</option>
+<option value="25">25</option>
+<option value="26">26</option>
+<option value="27">27</option>
+<option value="28">28</option>
+<option value="29">29</option>
+<option value="30">30</option>
+<option value="31" selected="selected">31</option>
+</select>
+<select name="mydate_year" id="id_mydate_year">
+<option value="2007">2007</option>
+<option value="2008">2008</option>
+<option value="2009">2009</option>
+<option value="2010" selected="selected">2010</option>
+<option value="2011">2011</option>
+<option value="2012">2012</option>
+<option value="2013">2013</option>
+<option value="2014">2014</option>
+<option value="2015">2015</option>
+<option value="2016">2016</option>
+</select>""")
+
+ # Using a SelectDateWidget in a form:
+ w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016'), required=False)
+ self.assertHTMLEqual(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>
+<option value="3">March</option>
+<option value="4">April</option>
+<option value="5">May</option>
+<option value="6">June</option>
+<option value="7">July</option>
+<option value="8">August</option>
+<option value="9">September</option>
+<option value="10">October</option>
+<option value="11">November</option>
+<option value="12">December</option>
+</select>
+<select name="mydate_day" id="id_mydate_day">
+<option value="0">---</option>
+<option value="1">1</option>
+<option value="2">2</option>
+<option value="3">3</option>
+<option value="4">4</option>
+<option value="5">5</option>
+<option value="6">6</option>
+<option value="7">7</option>
+<option value="8">8</option>
+<option value="9">9</option>
+<option value="10">10</option>
+<option value="11">11</option>
+<option value="12">12</option>
+<option value="13">13</option>
+<option value="14">14</option>
+<option value="15">15</option>
+<option value="16">16</option>
+<option value="17">17</option>
+<option value="18">18</option>
+<option value="19">19</option>
+<option value="20">20</option>
+<option value="21">21</option>
+<option value="22">22</option>
+<option value="23">23</option>
+<option value="24">24</option>
+<option value="25">25</option>
+<option value="26">26</option>
+<option value="27">27</option>
+<option value="28">28</option>
+<option value="29">29</option>
+<option value="30">30</option>
+<option value="31">31</option>
+</select>
+<select name="mydate_year" id="id_mydate_year">
+<option value="0">---</option>
+<option value="2007">2007</option>
+<option value="2008">2008</option>
+<option value="2009">2009</option>
+<option value="2010">2010</option>
+<option value="2011">2011</option>
+<option value="2012">2012</option>
+<option value="2013">2013</option>
+<option value="2014">2014</option>
+<option value="2015">2015</option>
+<option value="2016">2016</option>
+</select>""")
+ self.assertHTMLEqual(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>
+<option value="3">March</option>
+<option value="4" selected="selected">April</option>
+<option value="5">May</option>
+<option value="6">June</option>
+<option value="7">July</option>
+<option value="8">August</option>
+<option value="9">September</option>
+<option value="10">October</option>
+<option value="11">November</option>
+<option value="12">December</option>
+</select>
+<select name="mydate_day" id="id_mydate_day">
+<option value="0">---</option>
+<option value="1">1</option>
+<option value="2">2</option>
+<option value="3">3</option>
+<option value="4">4</option>
+<option value="5">5</option>
+<option value="6">6</option>
+<option value="7">7</option>
+<option value="8">8</option>
+<option value="9">9</option>
+<option value="10">10</option>
+<option value="11">11</option>
+<option value="12">12</option>
+<option value="13">13</option>
+<option value="14">14</option>
+<option value="15" selected="selected">15</option>
+<option value="16">16</option>
+<option value="17">17</option>
+<option value="18">18</option>
+<option value="19">19</option>
+<option value="20">20</option>
+<option value="21">21</option>
+<option value="22">22</option>
+<option value="23">23</option>
+<option value="24">24</option>
+<option value="25">25</option>
+<option value="26">26</option>
+<option value="27">27</option>
+<option value="28">28</option>
+<option value="29">29</option>
+<option value="30">30</option>
+<option value="31">31</option>
+</select>
+<select name="mydate_year" id="id_mydate_year">
+<option value="0">---</option>
+<option value="2007">2007</option>
+<option value="2008">2008</option>
+<option value="2009">2009</option>
+<option value="2010" selected="selected">2010</option>
+<option value="2011">2011</option>
+<option value="2012">2012</option>
+<option value="2013">2013</option>
+<option value="2014">2014</option>
+<option value="2015">2015</option>
+<option value="2016">2016</option>
+</select>""")
+
+ 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.assertHTMLEqual(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))
+
+ # Invalid dates shouldn't be allowed
+ c = GetDate({'mydate_month':'2', 'mydate_day':'31', 'mydate_year':'2010'})
+ self.assertFalse(c.is_valid())
+ self.assertEqual(c.errors, {'mydate': ['Enter a valid date.']})
+
+ # label tag is correctly associated with month dropdown
+ d = GetDate({'mydate_month':'1', 'mydate_day':'1', 'mydate_year':'2010'})
+ self.assertTrue('<label for="id_mydate_month">' in d.as_p())
+
+ 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.strptime(data[2], "%Y-%m-%d %H:%M:%S")]
+ return [None, None, None]
+
+ def format_output(self, rendered_widgets):
+ return '\n'.join(rendered_widgets)
+
+ w = ComplexMultiWidget()
+ self.assertHTMLEqual(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)
+ self.assertEqual(f.clean(['some text', ['J','P'], ['2007-04-25','6:24:00']]), 'some text,JP,2007-04-25 06:24:00')
+ self.assertFormErrors(['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(['This field is required.'], f.clean, ['some text',['JP']])
+
+ # test with no initial data
+ self.assertTrue(f._has_changed(None, ['some text', ['J','P'], ['2007-04-25','6:24:00']]))
+
+ # test when the data is the same as initial
+ self.assertFalse(f._has_changed('some text,JP,2007-04-25 06:24:00',
+ ['some text', ['J','P'], ['2007-04-25','6:24:00']]))
+
+ # test when the first widget's data has changed
+ self.assertTrue(f._has_changed('some text,JP,2007-04-25 06:24:00',
+ ['other text', ['J','P'], ['2007-04-25','6:24:00']]))
+
+ # test when the last widget's data has changed. this ensures that it is not
+ # short circuiting while testing the widgets.
+ self.assertTrue(f._has_changed('some text,JP,2007-04-25 06:24:00',
+ ['some text', ['J','P'], ['2009-04-25','11:44:00']]))
+
+
+ class ComplexFieldForm(Form):
+ field1 = ComplexField(widget=w)
+
+ f = ComplexFieldForm()
+ self.assertHTMLEqual(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.assertHTMLEqual(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'], 'some text,JP,2007-04-25 06:24:00')
+
+ def test_ipaddress(self):
+ f = IPAddressField()
+ self.assertFormErrors(['This field is required.'], f.clean, '')
+ self.assertFormErrors(['This field is required.'], f.clean, None)
+ self.assertEqual(f.clean(' 127.0.0.1'), '127.0.0.1')
+ self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, 'foo')
+ self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '127.0.0.')
+ self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5')
+ self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '256.125.1.5')
+
+ f = IPAddressField(required=False)
+ self.assertEqual(f.clean(''), '')
+ self.assertEqual(f.clean(None), '')
+ self.assertEqual(f.clean(' 127.0.0.1'), '127.0.0.1')
+ self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, 'foo')
+ self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '127.0.0.')
+ self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5')
+ self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '256.125.1.5')
+
+ def test_generic_ipaddress_invalid_arguments(self):
+ self.assertRaises(ValueError, GenericIPAddressField, protocol="hamster")
+ self.assertRaises(ValueError, GenericIPAddressField, protocol="ipv4", unpack_ipv4=True)
+
+ def test_generic_ipaddress_as_generic(self):
+ # The edge cases of the IPv6 validation code are not deeply tested
+ # here, they are covered in the tests for django.utils.ipv6
+ f = GenericIPAddressField()
+ self.assertFormErrors(['This field is required.'], f.clean, '')
+ self.assertFormErrors(['This field is required.'], f.clean, None)
+ self.assertEqual(f.clean(' 127.0.0.1 '), '127.0.0.1')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, 'foo')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '127.0.0.')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1.2.3.4.5')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '256.125.1.5')
+ self.assertEqual(f.clean(' fe80::223:6cff:fe8a:2e8a '), 'fe80::223:6cff:fe8a:2e8a')
+ self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '12345:2:3:4')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1::2:3::4')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, 'foo::223:6cff:fe8a:2e8a')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1::2:3:4:5:6:7:8')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1:2')
+
+ def test_generic_ipaddress_as_ipv4_only(self):
+ f = GenericIPAddressField(protocol="IPv4")
+ self.assertFormErrors(['This field is required.'], f.clean, '')
+ self.assertFormErrors(['This field is required.'], f.clean, None)
+ self.assertEqual(f.clean(' 127.0.0.1 '), '127.0.0.1')
+ self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, 'foo')
+ self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '127.0.0.')
+ self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5')
+ self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '256.125.1.5')
+ self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, 'fe80::223:6cff:fe8a:2e8a')
+ self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '2a02::223:6cff:fe8a:2e8a')
+
+ def test_generic_ipaddress_as_ipv6_only(self):
+ f = GenericIPAddressField(protocol="IPv6")
+ self.assertFormErrors(['This field is required.'], f.clean, '')
+ self.assertFormErrors(['This field is required.'], f.clean, None)
+ self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '127.0.0.1')
+ self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, 'foo')
+ self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '127.0.0.')
+ self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '1.2.3.4.5')
+ self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '256.125.1.5')
+ self.assertEqual(f.clean(' fe80::223:6cff:fe8a:2e8a '), 'fe80::223:6cff:fe8a:2e8a')
+ self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a')
+ self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '12345:2:3:4')
+ self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '1::2:3::4')
+ self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, 'foo::223:6cff:fe8a:2e8a')
+ self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '1::2:3:4:5:6:7:8')
+ self.assertFormErrors(['Enter a valid IPv6 address.'], f.clean, '1:2')
+
+ def test_generic_ipaddress_as_generic_not_required(self):
+ f = GenericIPAddressField(required=False)
+ self.assertEqual(f.clean(''), '')
+ self.assertEqual(f.clean(None), '')
+ self.assertEqual(f.clean('127.0.0.1'), '127.0.0.1')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, 'foo')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '127.0.0.')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1.2.3.4.5')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '256.125.1.5')
+ self.assertEqual(f.clean(' fe80::223:6cff:fe8a:2e8a '), 'fe80::223:6cff:fe8a:2e8a')
+ self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '12345:2:3:4')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1::2:3::4')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, 'foo::223:6cff:fe8a:2e8a')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1::2:3:4:5:6:7:8')
+ self.assertFormErrors(['Enter a valid IPv4 or IPv6 address.'], f.clean, '1:2')
+
+ def test_generic_ipaddress_normalization(self):
+ # Test the normalising code
+ f = GenericIPAddressField()
+ self.assertEqual(f.clean(' ::ffff:0a0a:0a0a '), '::ffff:10.10.10.10')
+ self.assertEqual(f.clean(' ::ffff:10.10.10.10 '), '::ffff:10.10.10.10')
+ self.assertEqual(f.clean(' 2001:000:a:0000:0:fe:fe:beef '), '2001:0:a::fe:fe:beef')
+ self.assertEqual(f.clean(' 2001::a:0000:0:fe:fe:beef '), '2001:0:a::fe:fe:beef')
+
+ f = GenericIPAddressField(unpack_ipv4=True)
+ self.assertEqual(f.clean(' ::ffff:0a0a:0a0a'), '10.10.10.10')
+
+ def test_smart_text(self):
+ class Test:
+ if six.PY3:
+ def __str__(self):
+ return 'ŠĐĆŽćžšđ'
+ else:
+ def __str__(self):
+ return 'ŠĐĆŽćžšđ'.encode('utf-8')
+
+ class TestU:
+ if six.PY3:
+ def __str__(self):
+ return 'ŠĐĆŽćžšđ'
+ def __bytes__(self):
+ return b'Foo'
+ else:
+ def __str__(self):
+ return b'Foo'
+ def __unicode__(self):
+ return '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111'
+
+ self.assertEqual(smart_text(Test()), '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111')
+ self.assertEqual(smart_text(TestU()), '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111')
+ self.assertEqual(smart_text(1), '1')
+ self.assertEqual(smart_text('foo'), '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'], 'sirrobin')
+
+ def test_overriding_errorlist(self):
+ @python_2_unicode_compatible
+ class DivErrorList(ErrorList):
+ def __str__(self):
+ return self.as_divs()
+
+ def as_divs(self):
+ if not self: return ''
+ return '<div class="errorlist">%s</div>' % ''.join(['<div class="error">%s</div>' % force_text(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.assertHTMLEqual(f.as_p(), """<p>Name: <input type="text" name="name" maxlength="50" /></p>
+<div class="errorlist"><div class="error">Enter a valid email address.</div></div>
+<p>Email: <input type="email" 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())
+
+ def test_field_not_required(self):
+ b = GetNotRequiredDate({
+ 'mydate_year': '',
+ 'mydate_month': '',
+ 'mydate_day': ''
+ })
+ self.assertFalse(b.has_changed())
+
+
+@override_settings(USE_L10N=True)
+class FormsExtraL10NTestCase(TestCase):
+ def setUp(self):
+ super(FormsExtraL10NTestCase, self).setUp()
+ translation.activate('nl')
+
+ def tearDown(self):
+ translation.deactivate()
+ super(FormsExtraL10NTestCase, self).tearDown()
+
+ 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')
+
+ self.assertHTMLEqual(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>
+<option value="3">3</option>
+<option value="4">4</option>
+<option value="5">5</option>
+<option value="6">6</option>
+<option value="7">7</option>
+<option value="8">8</option>
+<option value="9">9</option>
+<option value="10">10</option>
+<option value="11">11</option>
+<option value="12">12</option>
+<option value="13" selected="selected">13</option>
+<option value="14">14</option>
+<option value="15">15</option>
+<option value="16">16</option>
+<option value="17">17</option>
+<option value="18">18</option>
+<option value="19">19</option>
+<option value="20">20</option>
+<option value="21">21</option>
+<option value="22">22</option>
+<option value="23">23</option>
+<option value="24">24</option>
+<option value="25">25</option>
+<option value="26">26</option>
+<option value="27">27</option>
+<option value="28">28</option>
+<option value="29">29</option>
+<option value="30">30</option>
+<option value="31">31</option>
+</select>
+<select name="date_month" id="id_date_month">
+<option value="0">---</option>
+<option value="1">januari</option>
+<option value="2">februari</option>
+<option value="3">maart</option>
+<option value="4">april</option>
+<option value="5">mei</option>
+<option value="6">juni</option>
+<option value="7">juli</option>
+<option value="8" selected="selected">augustus</option>
+<option value="9">september</option>
+<option value="10">oktober</option>
+<option value="11">november</option>
+<option value="12">december</option>
+</select>
+<select name="date_year" id="id_date_year">
+<option value="0">---</option>
+<option value="2007">2007</option>
+<option value="2008">2008</option>
+<option value="2009">2009</option>
+<option value="2010" selected="selected">2010</option>
+<option value="2011">2011</option>
+<option value="2012">2012</option>
+<option value="2013">2013</option>
+<option value="2014">2014</option>
+<option value="2015">2015</option>
+<option value="2016">2016</option>
+</select>""")
+
+ # 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')
+
+ def test_l10n_date_changed(self):
+ """
+ Ensure that DateField._has_changed() with SelectDateWidget works
+ correctly with a localized date format.
+ Refs #17165.
+ """
+ # With Field.show_hidden_initial=False -----------------------
+ b = GetDate({
+ 'mydate_year': '2008',
+ 'mydate_month': '4',
+ 'mydate_day': '1',
+ }, initial={'mydate': datetime.date(2008, 4, 1)})
+ self.assertFalse(b.has_changed())
+
+ b = GetDate({
+ 'mydate_year': '2008',
+ 'mydate_month': '4',
+ 'mydate_day': '2',
+ }, initial={'mydate': datetime.date(2008, 4, 1)})
+ self.assertTrue(b.has_changed())
+
+ # With Field.show_hidden_initial=True ------------------------
+ b = GetDateShowHiddenInitial({
+ 'mydate_year': '2008',
+ 'mydate_month': '4',
+ 'mydate_day': '1',
+ 'initial-mydate': HiddenInput()._format_value(datetime.date(2008, 4, 1))
+ }, initial={'mydate': datetime.date(2008, 4, 1)})
+ self.assertFalse(b.has_changed())
+
+ b = GetDateShowHiddenInitial({
+ 'mydate_year': '2008',
+ 'mydate_month': '4',
+ 'mydate_day': '22',
+ 'initial-mydate': HiddenInput()._format_value(datetime.date(2008, 4, 1))
+ }, initial={'mydate': datetime.date(2008, 4, 1)})
+ self.assertTrue(b.has_changed())
+
+ b = GetDateShowHiddenInitial({
+ 'mydate_year': '2008',
+ 'mydate_month': '4',
+ 'mydate_day': '22',
+ 'initial-mydate': HiddenInput()._format_value(datetime.date(2008, 4, 1))
+ }, initial={'mydate': datetime.date(2008, 4, 22)})
+ self.assertTrue(b.has_changed())
+
+ b = GetDateShowHiddenInitial({
+ 'mydate_year': '2008',
+ 'mydate_month': '4',
+ 'mydate_day': '22',
+ 'initial-mydate': HiddenInput()._format_value(datetime.date(2008, 4, 22))
+ }, initial={'mydate': datetime.date(2008, 4, 1)})
+ self.assertFalse(b.has_changed())
+
+ def test_l10n_invalid_date_in(self):
+ # Invalid dates shouldn't be allowed
+ a = GetDate({'mydate_month':'2', 'mydate_day':'31', 'mydate_year':'2010'})
+ self.assertFalse(a.is_valid())
+ # 'Geef een geldige datum op.' = 'Enter a valid date.'
+ self.assertEqual(a.errors, {'mydate': ['Geef een geldige datum op.']})
+
+ def test_form_label_association(self):
+ # label tag is correctly associated with first rendered dropdown
+ a = GetDate({'mydate_month':'1', 'mydate_day':'1', 'mydate_year':'2010'})
+ self.assertTrue('<label for="id_mydate_day">' in a.as_p())
diff --git a/tests/forms_tests/tests/fields.py b/tests/forms_tests/tests/fields.py
new file mode 100644
index 0000000000..b0e299983b
--- /dev/null
+++ b/tests/forms_tests/tests/fields.py
@@ -0,0 +1,1190 @@
+# -*- coding: utf-8 -*-
+"""
+##########
+# Fields #
+##########
+
+Each Field class does some sort of validation. Each Field has a clean() method,
+which either raises django.forms.ValidationError or returns the "clean"
+data -- usually a Unicode object, but, in some rare cases, a list.
+
+Each Field's __init__() takes at least these parameters:
+ required -- Boolean that specifies whether the field is required.
+ True by default.
+ widget -- A Widget class, or instance of a Widget class, that should be
+ used for this Field when displaying it. Each Field has a default
+ Widget that it'll use if you don't specify this. In most cases,
+ the default widget is TextInput.
+ label -- A verbose name for this field, for use in displaying this field in
+ a form. By default, Django will use a "pretty" version of the form
+ field name, if the Field is part of a Form.
+ initial -- A value to use in this Field's initial display. This value is
+ *not* used as a fallback if data isn't given.
+
+Other than that, the Field subclasses have class-specific options for
+__init__(). For example, CharField has a max_length option.
+"""
+from __future__ import unicode_literals
+
+import datetime
+import pickle
+import re
+import os
+from decimal import Decimal
+
+from django.core.files.uploadedfile import SimpleUploadedFile
+from django.forms import *
+from django.test import SimpleTestCase
+from django.utils import six
+from django.utils._os import upath
+
+
+def fix_os_paths(x):
+ if isinstance(x, six.string_types):
+ return x.replace('\\', '/')
+ elif isinstance(x, tuple):
+ return tuple(fix_os_paths(list(x)))
+ elif isinstance(x, list):
+ return [fix_os_paths(y) for y in x]
+ else:
+ return x
+
+
+class FieldsTests(SimpleTestCase):
+
+ def assertWidgetRendersTo(self, field, to):
+ class _Form(Form):
+ f = field
+ self.assertHTMLEqual(str(_Form()['f']), to)
+
+ def test_field_sets_widget_is_required(self):
+ self.assertTrue(Field(required=True).widget.is_required)
+ self.assertFalse(Field(required=False).widget.is_required)
+
+ # CharField ###################################################################
+
+ def test_charfield_1(self):
+ f = CharField()
+ self.assertEqual('1', f.clean(1))
+ self.assertEqual('hello', f.clean('hello'))
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+ self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3]))
+ self.assertEqual(f.max_length, None)
+ self.assertEqual(f.min_length, None)
+
+ def test_charfield_2(self):
+ f = CharField(required=False)
+ self.assertEqual('1', f.clean(1))
+ self.assertEqual('hello', f.clean('hello'))
+ self.assertEqual('', f.clean(None))
+ self.assertEqual('', f.clean(''))
+ self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3]))
+ self.assertEqual(f.max_length, None)
+ self.assertEqual(f.min_length, None)
+
+ def test_charfield_3(self):
+ f = CharField(max_length=10, required=False)
+ self.assertEqual('12345', f.clean('12345'))
+ self.assertEqual('1234567890', f.clean('1234567890'))
+ self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", f.clean, '1234567890a')
+ self.assertEqual(f.max_length, 10)
+ self.assertEqual(f.min_length, None)
+
+ def test_charfield_4(self):
+ f = CharField(min_length=10, required=False)
+ self.assertEqual('', f.clean(''))
+ self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 5).'", f.clean, '12345')
+ self.assertEqual('1234567890', f.clean('1234567890'))
+ self.assertEqual('1234567890a', f.clean('1234567890a'))
+ self.assertEqual(f.max_length, None)
+ self.assertEqual(f.min_length, 10)
+
+ def test_charfield_5(self):
+ f = CharField(min_length=10, required=True)
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+ self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 5).'", f.clean, '12345')
+ self.assertEqual('1234567890', f.clean('1234567890'))
+ self.assertEqual('1234567890a', f.clean('1234567890a'))
+ self.assertEqual(f.max_length, None)
+ self.assertEqual(f.min_length, 10)
+
+ def test_charfield_widget_attrs(self):
+ """
+ Ensure that CharField.widget_attrs() always returns a dictionary.
+ Refs #15912
+ """
+ # Return an empty dictionary if max_length is None
+ f = CharField()
+ self.assertEqual(f.widget_attrs(TextInput()), {})
+
+ # Or if the widget is not TextInput or PasswordInput
+ f = CharField(max_length=10)
+ self.assertEqual(f.widget_attrs(HiddenInput()), {})
+
+ # Otherwise, return a maxlength attribute equal to max_length
+ self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10'})
+ self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10'})
+
+ # IntegerField ################################################################
+
+ def test_integerfield_1(self):
+ f = IntegerField()
+ self.assertWidgetRendersTo(f, '<input type="number" name="f" id="id_f" />')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+ self.assertEqual(1, f.clean('1'))
+ self.assertEqual(True, isinstance(f.clean('1'), int))
+ self.assertEqual(23, f.clean('23'))
+ self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, 'a')
+ self.assertEqual(42, f.clean(42))
+ self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, 3.14)
+ self.assertEqual(1, f.clean('1 '))
+ self.assertEqual(1, f.clean(' 1'))
+ self.assertEqual(1, f.clean(' 1 '))
+ self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, '1a')
+ self.assertEqual(f.max_value, None)
+ self.assertEqual(f.min_value, None)
+
+ def test_integerfield_2(self):
+ f = IntegerField(required=False)
+ self.assertEqual(None, f.clean(''))
+ self.assertEqual('None', repr(f.clean('')))
+ self.assertEqual(None, f.clean(None))
+ self.assertEqual('None', repr(f.clean(None)))
+ self.assertEqual(1, f.clean('1'))
+ self.assertEqual(True, isinstance(f.clean('1'), int))
+ self.assertEqual(23, f.clean('23'))
+ self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, 'a')
+ self.assertEqual(1, f.clean('1 '))
+ self.assertEqual(1, f.clean(' 1'))
+ self.assertEqual(1, f.clean(' 1 '))
+ self.assertRaisesMessage(ValidationError, "'Enter a whole number.'", f.clean, '1a')
+ self.assertEqual(f.max_value, None)
+ self.assertEqual(f.min_value, None)
+
+ def test_integerfield_3(self):
+ f = IntegerField(max_value=10)
+ self.assertWidgetRendersTo(f, '<input max="10" type="number" name="f" id="id_f" />')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+ self.assertEqual(1, f.clean(1))
+ self.assertEqual(10, f.clean(10))
+ self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'", f.clean, 11)
+ self.assertEqual(10, f.clean('10'))
+ self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 10.'", f.clean, '11')
+ self.assertEqual(f.max_value, 10)
+ self.assertEqual(f.min_value, None)
+
+ def test_integerfield_4(self):
+ f = IntegerField(min_value=10)
+ self.assertWidgetRendersTo(f, '<input id="id_f" type="number" name="f" min="10" />')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+ self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'", f.clean, 1)
+ self.assertEqual(10, f.clean(10))
+ self.assertEqual(11, f.clean(11))
+ self.assertEqual(10, f.clean('10'))
+ self.assertEqual(11, f.clean('11'))
+ self.assertEqual(f.max_value, None)
+ self.assertEqual(f.min_value, 10)
+
+ def test_integerfield_5(self):
+ f = IntegerField(min_value=10, max_value=20)
+ self.assertWidgetRendersTo(f, '<input id="id_f" max="20" type="number" name="f" min="10" />')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+ self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 10.'", f.clean, 1)
+ self.assertEqual(10, f.clean(10))
+ self.assertEqual(11, f.clean(11))
+ self.assertEqual(10, f.clean('10'))
+ self.assertEqual(11, f.clean('11'))
+ self.assertEqual(20, f.clean(20))
+ self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 20.'", f.clean, 21)
+ self.assertEqual(f.max_value, 20)
+ self.assertEqual(f.min_value, 10)
+
+ def test_integerfield_localized(self):
+ """
+ Make sure localized IntegerField's widget renders to a text input with
+ no number input specific attributes.
+ """
+ f1 = IntegerField(localize=True)
+ self.assertWidgetRendersTo(f1, '<input id="id_f" name="f" type="text" />')
+
+ # FloatField ##################################################################
+
+ def test_floatfield_1(self):
+ f = FloatField()
+ self.assertWidgetRendersTo(f, '<input step="any" type="number" name="f" id="id_f" />')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+ self.assertEqual(1.0, f.clean('1'))
+ self.assertEqual(True, isinstance(f.clean('1'), float))
+ self.assertEqual(23.0, f.clean('23'))
+ self.assertEqual(3.1400000000000001, f.clean('3.14'))
+ self.assertEqual(3.1400000000000001, f.clean(3.14))
+ self.assertEqual(42.0, f.clean(42))
+ self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'a')
+ self.assertEqual(1.0, f.clean('1.0 '))
+ self.assertEqual(1.0, f.clean(' 1.0'))
+ self.assertEqual(1.0, f.clean(' 1.0 '))
+ self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '1.0a')
+ self.assertEqual(f.max_value, None)
+ self.assertEqual(f.min_value, None)
+
+ 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'))
+ self.assertEqual(f.max_value, None)
+ self.assertEqual(f.min_value, None)
+
+ def test_floatfield_3(self):
+ f = FloatField(max_value=1.5, min_value=0.5)
+ self.assertWidgetRendersTo(f, '<input step="any" name="f" min="0.5" max="1.5" type="number" id="id_f" />')
+ self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'", f.clean, '1.6')
+ self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'", f.clean, '0.4')
+ self.assertEqual(1.5, f.clean('1.5'))
+ self.assertEqual(0.5, f.clean('0.5'))
+ self.assertEqual(f.max_value, 1.5)
+ self.assertEqual(f.min_value, 0.5)
+
+ def test_floatfield_localized(self):
+ """
+ Make sure localized FloatField's widget renders to a text input with
+ no number input specific attributes.
+ """
+ f = FloatField(localize=True)
+ self.assertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" />')
+
+ # DecimalField ################################################################
+
+ def test_decimalfield_1(self):
+ f = DecimalField(max_digits=4, decimal_places=2)
+ self.assertWidgetRendersTo(f, '<input id="id_f" step="0.01" type="number" name="f" maxlength="6" />')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+ self.assertEqual(f.clean('1'), Decimal("1"))
+ self.assertEqual(True, isinstance(f.clean('1'), Decimal))
+ self.assertEqual(f.clean('23'), Decimal("23"))
+ self.assertEqual(f.clean('3.14'), Decimal("3.14"))
+ self.assertEqual(f.clean(3.14), Decimal("3.14"))
+ self.assertEqual(f.clean(Decimal('3.14')), Decimal("3.14"))
+ self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'NaN')
+ self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'Inf')
+ self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '-Inf')
+ self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'a')
+ self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, 'łąść')
+ self.assertEqual(f.clean('1.0 '), Decimal("1.0"))
+ self.assertEqual(f.clean(' 1.0'), Decimal("1.0"))
+ self.assertEqual(f.clean(' 1.0 '), Decimal("1.0"))
+ self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '1.0a')
+ self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '123.45')
+ self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '1.234')
+ self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 digits before the decimal point.'", f.clean, '123.4')
+ self.assertEqual(f.clean('-12.34'), Decimal("-12.34"))
+ self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '-123.45')
+ self.assertEqual(f.clean('-.12'), Decimal("-0.12"))
+ self.assertEqual(f.clean('-00.12'), Decimal("-0.12"))
+ self.assertEqual(f.clean('-000.12'), Decimal("-0.12"))
+ self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '-000.123')
+ self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '-000.12345')
+ self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '--0.12')
+ self.assertEqual(f.max_digits, 4)
+ self.assertEqual(f.decimal_places, 2)
+ self.assertEqual(f.max_value, None)
+ self.assertEqual(f.min_value, None)
+
+ 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"))
+ self.assertEqual(f.max_digits, 4)
+ self.assertEqual(f.decimal_places, 2)
+ self.assertEqual(f.max_value, None)
+ self.assertEqual(f.min_value, None)
+
+ def test_decimalfield_3(self):
+ f = DecimalField(max_digits=4, decimal_places=2, max_value=Decimal('1.5'), min_value=Decimal('0.5'))
+ self.assertWidgetRendersTo(f, '<input step="0.01" name="f" min="0.5" max="1.5" maxlength="6" type="number" id="id_f" />')
+ self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'", f.clean, '1.6')
+ self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'", f.clean, '0.4')
+ self.assertEqual(f.clean('1.5'), Decimal("1.5"))
+ self.assertEqual(f.clean('0.5'), Decimal("0.5"))
+ self.assertEqual(f.clean('.5'), Decimal("0.5"))
+ self.assertEqual(f.clean('00.50'), Decimal("0.50"))
+ self.assertEqual(f.max_digits, 4)
+ self.assertEqual(f.decimal_places, 2)
+ self.assertEqual(f.max_value, Decimal('1.5'))
+ self.assertEqual(f.min_value, Decimal('0.5'))
+
+ def test_decimalfield_4(self):
+ f = DecimalField(decimal_places=2)
+ self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '0.00000001')
+
+ 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"))
+ # But a leading 0 before the . doesn't count towards max_digits
+ self.assertEqual(f.clean('0000000.100'), Decimal("0.100"))
+ # Only leading whole zeros "collapse" to one digit.
+ self.assertEqual(f.clean('000000.02'), Decimal('0.02'))
+ self.assertRaisesMessage(ValidationError, "'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_6(self):
+ f = DecimalField(max_digits=2, decimal_places=2)
+ self.assertEqual(f.clean('.01'), Decimal(".01"))
+ self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 0 digits before the decimal point.'", f.clean, '1.1')
+
+ def test_decimalfield_localized(self):
+ """
+ Make sure localized DecimalField's widget renders to a text input with
+ no number input specific attributes.
+ """
+ f = DecimalField(localize=True)
+ self.assertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" />')
+
+ # DateField ###################################################################
+
+ 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)))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59)))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200)))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean('2006-10-25'))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean('10/25/2006'))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean('10/25/06'))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean('Oct 25 2006'))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean('October 25 2006'))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean('October 25, 2006'))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean('25 October 2006'))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean('25 October, 2006'))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '2006-4-31')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '200a-10-25')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '25/10/06')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+
+ 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_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)))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean('2006 10 25'))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '2006-10-25')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '10/25/2006')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, '10/25/06')
+
+ def test_datefield_4(self):
+ # Test whitespace stripping behavior (#5714)
+ f = DateField()
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean(' 10/25/2006 '))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean(' 10/25/06 '))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean(' Oct 25 2006 '))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean(' October 25 2006 '))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean(' October 25, 2006 '))
+ self.assertEqual(datetime.date(2006, 10, 25), f.clean(' 25 October 2006 '))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ' ')
+
+ def test_datefield_5(self):
+ # Test null bytes (#18982)
+ f = DateField()
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, 'a\x00b')
+
+ def test_datefield_changed(self):
+ format = '%d/%m/%Y'
+ f = DateField(input_formats=[format])
+ d = datetime.date(2007, 9, 17)
+ self.assertFalse(f._has_changed(d, '17/09/2007'))
+ self.assertFalse(f._has_changed(d.strftime(format), '17/09/2007'))
+
+ def test_datefield_strptime(self):
+ """Test that field.strptime doesn't raise an UnicodeEncodeError (#16123)"""
+ f = DateField()
+ try:
+ f.strptime('31 мая 2011', '%d-%b-%y')
+ except Exception as e:
+ # assertIsInstance or assertRaises cannot be used because UnicodeEncodeError
+ # is a subclass of ValueError
+ self.assertEqual(e.__class__, ValueError)
+
+ # TimeField ###################################################################
+
+ 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)))
+ self.assertEqual(datetime.time(14, 25), f.clean('14:25'))
+ self.assertEqual(datetime.time(14, 25, 59), f.clean('14:25:59'))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, 'hello')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, '1:24 p.m.')
+
+ 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)))
+ self.assertEqual(datetime.time(4, 25), f.clean('4:25 AM'))
+ self.assertEqual(datetime.time(16, 25), f.clean('4:25 PM'))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, '14:30:45')
+
+ def test_timefield_3(self):
+ f = TimeField()
+ # Test whitespace stripping behavior (#5714)
+ self.assertEqual(datetime.time(14, 25), f.clean(' 14:25 '))
+ self.assertEqual(datetime.time(14, 25, 59), f.clean(' 14:25:59 '))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ' ')
+
+ def test_timefield_changed(self):
+ t1 = datetime.time(12, 51, 34, 482548)
+ t2 = datetime.time(12, 51)
+ format = '%H:%M'
+ f = TimeField(input_formats=[format])
+ self.assertTrue(f._has_changed(t1, '12:51'))
+ self.assertFalse(f._has_changed(t2, '12:51'))
+
+ format = '%I:%M %p'
+ f = TimeField(input_formats=[format])
+ self.assertFalse(f._has_changed(t2.strftime(format), '12:51 PM'))
+
+ # DateTimeField ###############################################################
+
+ 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)))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59)))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200)))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006-10-25 14:30:45.000200'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006-10-25 14:30:45.0002'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('2006-10-25 14:30:45'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006-10-25 14:30:00'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006-10-25 14:30'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('2006-10-25'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('10/25/2006 14:30:45.000200'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('10/25/2006 14:30:45'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/2006 14:30:00'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/2006 14:30'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('10/25/2006'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('10/25/06 14:30:45.000200'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('10/25/06 14:30:45'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30:00'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30'))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('10/25/06'))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, 'hello')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, '2006-10-25 4:30 p.m.')
+
+ 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)))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59)))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200)))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006 10 25 2:30 PM'))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, '2006-10-25 14:30:45')
+
+ def test_datetimefield_3(self):
+ f = DateTimeField(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_datetimefield_4(self):
+ f = DateTimeField()
+ # Test whitespace stripping behavior (#5714)
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean(' 2006-10-25 14:30:45 '))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 2006-10-25 '))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean(' 10/25/2006 14:30:45 '))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(' 10/25/2006 14:30 '))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 10/25/2006 '))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean(' 10/25/06 14:30:45 '))
+ self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 10/25/06 '))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, ' ')
+
+ def test_datetimefield_5(self):
+ f = DateTimeField(input_formats=['%Y.%m.%d %H:%M:%S.%f'])
+ self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006.10.25 14:30:45.0002'))
+
+ def test_datetimefield_changed(self):
+ format = '%Y %m %d %I:%M %p'
+ f = DateTimeField(input_formats=[format])
+ d = datetime.datetime(2006, 9, 17, 14, 30, 0)
+ self.assertFalse(f._has_changed(d, '2006 09 17 2:30 PM'))
+ # Initial value may be a string from a hidden input
+ self.assertFalse(f._has_changed(d.strftime(format), '2006 09 17 2:30 PM'))
+
+ # RegexField ##################################################################
+
+ def test_regexfield_1(self):
+ f = RegexField('^\d[A-F]\d$')
+ self.assertEqual('2A2', f.clean('2A2'))
+ self.assertEqual('3F3', f.clean('3F3'))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '3G3')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, ' 2A2')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '2A2 ')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+
+ def test_regexfield_2(self):
+ f = RegexField('^\d[A-F]\d$', required=False)
+ self.assertEqual('2A2', f.clean('2A2'))
+ self.assertEqual('3F3', f.clean('3F3'))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '3G3')
+ self.assertEqual('', f.clean(''))
+
+ def test_regexfield_3(self):
+ f = RegexField(re.compile('^\d[A-F]\d$'))
+ self.assertEqual('2A2', f.clean('2A2'))
+ self.assertEqual('3F3', f.clean('3F3'))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '3G3')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, ' 2A2')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '2A2 ')
+
+ def test_regexfield_4(self):
+ f = RegexField('^\d\d\d\d$', error_message='Enter a four-digit number.')
+ self.assertEqual('1234', f.clean('1234'))
+ self.assertRaisesMessage(ValidationError, "'Enter a four-digit number.'", f.clean, '123')
+ self.assertRaisesMessage(ValidationError, "'Enter a four-digit number.'", f.clean, 'abcd')
+
+ def test_regexfield_5(self):
+ f = RegexField('^\d+$', min_length=5, max_length=10)
+ self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 5 characters (it has 3).'", f.clean, '123')
+ six.assertRaisesRegex(self, ValidationError, "'Ensure this value has at least 5 characters \(it has 3\)\.', u?'Enter a valid value\.'", f.clean, 'abc')
+ self.assertEqual('12345', f.clean('12345'))
+ self.assertEqual('1234567890', f.clean('1234567890'))
+ self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", f.clean, '12345678901')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '12345a')
+
+ def test_regexfield_6(self):
+ """
+ Ensure that it works with unicode characters.
+ Refs #.
+ """
+ f = RegexField('^\w+$')
+ self.assertEqual('éèøçÎÎ你好', f.clean('éèøçÎÎ你好'))
+
+ def test_change_regex_after_init(self):
+ f = RegexField('^[a-z]+$')
+ f.regex = '^\d+$'
+ self.assertEqual('1234', f.clean('1234'))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, 'abcd')
+
+ # EmailField ##################################################################
+ # See also validators tests for validate_email specific tests
+
+ def test_emailfield_1(self):
+ f = EmailField()
+ self.assertWidgetRendersTo(f, '<input type="email" name="f" id="id_f" />')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+ self.assertEqual('person@example.com', f.clean('person@example.com'))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'foo')
+ self.assertEqual('local@domain.with.idn.xyz\xe4\xf6\xfc\xdfabc.part.com',
+ f.clean('local@domain.with.idn.xyzäöüßabc.part.com'))
+
+ def test_email_regexp_for_performance(self):
+ f = EmailField()
+ # Check for runaway regex security problem. This will take for-freeking-ever
+ # if the security fix isn't in place.
+ addr = 'viewx3dtextx26qx3d@yahoo.comx26latlngx3d15854521645943074058'
+ self.assertEqual(addr, f.clean(addr))
+
+ def test_emailfield_not_required(self):
+ f = EmailField(required=False)
+ self.assertEqual('', f.clean(''))
+ self.assertEqual('', f.clean(None))
+ self.assertEqual('person@example.com', f.clean('person@example.com'))
+ self.assertEqual('example@example.com', f.clean(' example@example.com \t \t '))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'foo')
+
+ def test_emailfield_min_max_length(self):
+ f = EmailField(min_length=10, max_length=15)
+ self.assertWidgetRendersTo(f, '<input id="id_f" type="email" name="f" maxlength="15" />')
+ self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 9).'", f.clean, 'a@foo.com')
+ self.assertEqual('alf@foo.com', f.clean('alf@foo.com'))
+ self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 15 characters (it has 20).'", f.clean, 'alf123456788@foo.com')
+
+ # FileField ##################################################################
+
+ def test_filefield_1(self):
+ f = FileField()
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '', '')
+ self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf'))
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None, '')
+ self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
+ self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, SimpleUploadedFile('', b''))
+ self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, SimpleUploadedFile('', b''), '')
+ self.assertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf'))
+ self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, 'some content that is not a file')
+ self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'", f.clean, SimpleUploadedFile('name', None))
+ self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'", f.clean, SimpleUploadedFile('name', b''))
+ self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content'))))
+ self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8')))))
+ self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content'), 'files/test4.pdf')))
+
+ def test_filefield_2(self):
+ f = FileField(max_length = 5)
+ self.assertRaisesMessage(ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'", f.clean, SimpleUploadedFile('test_maxlength.txt', b'hello world'))
+ self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf'))
+ self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
+ self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content'))))
+
+ def test_filefield_3(self):
+ f = FileField(allow_empty_file=True)
+ self.assertEqual(SimpleUploadedFile,
+ type(f.clean(SimpleUploadedFile('name', b''))))
+
+ def test_filefield_changed(self):
+ '''
+ Test for the behavior of _has_changed for FileField. 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 FileField it is ignored.
+ '''
+ f = FileField()
+
+ # No file was uploaded and no initial data.
+ self.assertFalse(f._has_changed('', None))
+
+ # A file was uploaded and no initial data.
+ self.assertTrue(f._has_changed('', {'filename': 'resume.txt', 'content': 'My resume'}))
+
+ # A file was not uploaded, but there is initial data
+ self.assertFalse(f._has_changed('resume.txt', None))
+
+ # A file was uploaded and there is initial data (file identity is not dealt
+ # with here)
+ self.assertTrue(f._has_changed('resume.txt', {'filename': 'resume.txt', 'content': 'My resume'}))
+
+
+ # URLField ##################################################################
+
+ def test_urlfield_1(self):
+ f = URLField()
+ self.assertWidgetRendersTo(f, '<input type="url" name="f" id="id_f" />')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+ self.assertEqual('http://localhost/', f.clean('http://localhost'))
+ self.assertEqual('http://example.com/', f.clean('http://example.com'))
+ self.assertEqual('http://example.com./', f.clean('http://example.com.'))
+ self.assertEqual('http://www.example.com/', f.clean('http://www.example.com'))
+ self.assertEqual('http://www.example.com:8000/test', f.clean('http://www.example.com:8000/test'))
+ self.assertEqual('http://valid-with-hyphens.com/', f.clean('valid-with-hyphens.com'))
+ self.assertEqual('http://subdomain.domain.com/', f.clean('subdomain.domain.com'))
+ self.assertEqual('http://200.8.9.10/', f.clean('http://200.8.9.10'))
+ self.assertEqual('http://200.8.9.10:8000/test', f.clean('http://200.8.9.10:8000/test'))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'foo')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example.')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'com.')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, '.')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://.com')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://invalid-.com')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://-invalid.com')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://inv-.alid-.com')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://inv-.-alid.com')
+ self.assertEqual('http://valid-----hyphens.com/', f.clean('http://valid-----hyphens.com'))
+ self.assertEqual('http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah'))
+ self.assertEqual('http://www.example.com/s/http://code.djangoproject.com/ticket/13804', f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804'))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, '[a')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://[a')
+
+ def test_url_regex_ticket11198(self):
+ f = URLField()
+ # hangs "forever" if catastrophic backtracking in ticket:#11198 not fixed
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://%s' % ("X"*200,))
+
+ # a second test, to make sure the problem is really addressed, even on
+ # domains that don't fail the domain label length check in the regex
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://%s' % ("X"*60,))
+
+ def test_urlfield_2(self):
+ f = URLField(required=False)
+ self.assertEqual('', f.clean(''))
+ self.assertEqual('', f.clean(None))
+ self.assertEqual('http://example.com/', f.clean('http://example.com'))
+ self.assertEqual('http://www.example.com/', f.clean('http://www.example.com'))
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'foo')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://example.')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://.com')
+
+ def test_urlfield_5(self):
+ f = URLField(min_length=15, max_length=20)
+ self.assertWidgetRendersTo(f, '<input id="id_f" type="url" name="f" maxlength="20" />')
+ self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 15 characters (it has 13).'", f.clean, 'http://f.com')
+ self.assertEqual('http://example.com/', f.clean('http://example.com'))
+ self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 38).'", f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com')
+
+ def test_urlfield_6(self):
+ f = URLField(required=False)
+ self.assertEqual('http://example.com/', f.clean('example.com'))
+ self.assertEqual('', f.clean(''))
+ self.assertEqual('https://example.com/', f.clean('https://example.com'))
+
+ def test_urlfield_7(self):
+ f = URLField()
+ self.assertEqual('http://example.com/', f.clean('http://example.com'))
+ self.assertEqual('http://example.com/test', f.clean('http://example.com/test'))
+
+ def test_urlfield_8(self):
+ # ticket #11826
+ f = URLField()
+ self.assertEqual('http://example.com/?some_param=some_value', f.clean('http://example.com?some_param=some_value'))
+
+ def test_urlfield_9(self):
+ f = URLField()
+ urls = (
+ 'http://עברית.idn.icann.org/',
+ 'http://sãopaulo.com/',
+ 'http://sãopaulo.com.br/',
+ 'http://пример.испытание/',
+ 'http://مثال.إختبار/',
+ 'http://例子.测试/',
+ 'http://例子.測試/',
+ 'http://उदाहरण.परीक्षा/',
+ 'http://例え.テスト/',
+ 'http://مثال.آزمایشی/',
+ 'http://실례.테스트/',
+ 'http://العربية.idn.icann.org/',
+ )
+ for url in urls:
+ # Valid IDN
+ self.assertEqual(url, f.clean(url))
+
+ def test_urlfield_10(self):
+ """Test URLField correctly validates IPv6 (#18779)."""
+ f = URLField()
+ urls = (
+ 'http://::/',
+ 'http://6:21b4:92/',
+ 'http://[12:34:3a53]/',
+ 'http://[a34:9238::]:8080/',
+ )
+ for url in urls:
+ self.assertEqual(url, f.clean(url))
+
+ def test_urlfield_not_string(self):
+ f = URLField(required=False)
+ self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 23)
+
+ # BooleanField ################################################################
+
+ def test_booleanfield_1(self):
+ f = BooleanField()
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+ self.assertEqual(True, f.clean(True))
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, False)
+ self.assertEqual(True, f.clean(1))
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, 0)
+ self.assertEqual(True, f.clean('Django rocks'))
+ self.assertEqual(True, f.clean('True'))
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, 'False')
+
+ def test_booleanfield_2(self):
+ f = BooleanField(required=False)
+ self.assertEqual(False, f.clean(''))
+ self.assertEqual(False, f.clean(None))
+ self.assertEqual(True, f.clean(True))
+ self.assertEqual(False, f.clean(False))
+ self.assertEqual(True, f.clean(1))
+ self.assertEqual(False, f.clean(0))
+ self.assertEqual(True, f.clean('1'))
+ self.assertEqual(False, f.clean('0'))
+ self.assertEqual(True, f.clean('Django rocks'))
+ self.assertEqual(False, f.clean('False'))
+ self.assertEqual(False, f.clean('false'))
+ self.assertEqual(False, f.clean('FaLsE'))
+
+ def test_boolean_picklable(self):
+ self.assertIsInstance(pickle.loads(pickle.dumps(BooleanField())), BooleanField)
+
+ def test_booleanfield_changed(self):
+ f = BooleanField()
+ self.assertFalse(f._has_changed(None, None))
+ self.assertFalse(f._has_changed(None, ''))
+ self.assertFalse(f._has_changed('', None))
+ self.assertFalse(f._has_changed('', ''))
+ self.assertTrue(f._has_changed(False, 'on'))
+ self.assertFalse(f._has_changed(True, 'on'))
+ self.assertTrue(f._has_changed(True, ''))
+ # Initial value may have mutated to a string due to show_hidden_initial (#19537)
+ self.assertTrue(f._has_changed('False', 'on'))
+
+ # ChoiceField #################################################################
+
+ def test_choicefield_1(self):
+ f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')])
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+ self.assertEqual('1', f.clean(1))
+ self.assertEqual('1', f.clean('1'))
+ self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, '3')
+
+ def test_choicefield_2(self):
+ f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
+ self.assertEqual('', f.clean(''))
+ self.assertEqual('', f.clean(None))
+ self.assertEqual('1', f.clean(1))
+ self.assertEqual('1', f.clean('1'))
+ self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, '3')
+
+ def test_choicefield_3(self):
+ f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')])
+ self.assertEqual('J', f.clean('J'))
+ self.assertRaisesMessage(ValidationError, "'Select a valid choice. John is not one of the available choices.'", f.clean, 'John')
+
+ def test_choicefield_4(self):
+ f = ChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')])
+ self.assertEqual('1', f.clean(1))
+ self.assertEqual('1', f.clean('1'))
+ self.assertEqual('3', f.clean(3))
+ self.assertEqual('3', f.clean('3'))
+ self.assertEqual('5', f.clean(5))
+ self.assertEqual('5', f.clean('5'))
+ self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, '6')
+
+ # TypedChoiceField ############################################################
+ # TypedChoiceField is just like ChoiceField, except that coerced types will
+ # be returned:
+
+ def test_typedchoicefield_1(self):
+ f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
+ self.assertEqual(1, f.clean('1'))
+ self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, '2')
+
+ 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_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_4(self):
+ # Even more weirdness: if you have a valid choice but your coercion function
+ # can't coerce, yo'll still get a validation error. Don't do this!
+ f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int)
+ self.assertRaisesMessage(ValidationError, "'Select a valid choice. B is not one of the available choices.'", f.clean, 'B')
+ # Required fields require values
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+
+ 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_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_1(self):
+ f = NullBooleanField()
+ self.assertEqual(None, f.clean(''))
+ self.assertEqual(True, f.clean(True))
+ self.assertEqual(False, f.clean(False))
+ self.assertEqual(None, f.clean(None))
+ self.assertEqual(False, f.clean('0'))
+ self.assertEqual(True, f.clean('1'))
+ self.assertEqual(None, f.clean('2'))
+ self.assertEqual(None, f.clean('3'))
+ self.assertEqual(None, f.clean('hello'))
+
+
+ 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)
+ hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False)
+ f = HiddenNullBooleanForm()
+ self.assertHTMLEqual('<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_3(self):
+ class HiddenNullBooleanForm(Form):
+ hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True)
+ hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False)
+ f = HiddenNullBooleanForm({ 'hidden_nullbool1': 'True', 'hidden_nullbool2': 'False' })
+ self.assertEqual(None, f.full_clean())
+ self.assertEqual(True, f.cleaned_data['hidden_nullbool1'])
+ self.assertEqual(False, f.cleaned_data['hidden_nullbool2'])
+
+ 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'))
+ class MySQLNullBooleanForm(Form):
+ nullbool0 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES))
+ nullbool1 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES))
+ nullbool2 = NullBooleanField(widget=RadioSelect(choices=NULLBOOL_CHOICES))
+ f = MySQLNullBooleanForm({ 'nullbool0': '1', 'nullbool1': '0', 'nullbool2': '' })
+ self.assertEqual(None, f.full_clean())
+ self.assertEqual(True, f.cleaned_data['nullbool0'])
+ self.assertEqual(False, f.cleaned_data['nullbool1'])
+ self.assertEqual(None, f.cleaned_data['nullbool2'])
+
+ def test_nullbooleanfield_changed(self):
+ f = NullBooleanField()
+ self.assertTrue(f._has_changed(False, None))
+ self.assertTrue(f._has_changed(None, False))
+ self.assertFalse(f._has_changed(None, None))
+ self.assertFalse(f._has_changed(False, False))
+ self.assertTrue(f._has_changed(True, False))
+ self.assertTrue(f._has_changed(True, None))
+ self.assertTrue(f._has_changed(True, False))
+
+ # MultipleChoiceField #########################################################
+
+ def test_multiplechoicefield_1(self):
+ f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')])
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+ self.assertEqual(['1'], f.clean([1]))
+ self.assertEqual(['1'], f.clean(['1']))
+ self.assertEqual(['1', '2'], f.clean(['1', '2']))
+ self.assertEqual(['1', '2'], f.clean([1, '2']))
+ self.assertEqual(['1', '2'], f.clean((1, '2')))
+ self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, [])
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, ())
+ self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, ['3'])
+
+ def test_multiplechoicefield_2(self):
+ f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
+ self.assertEqual([], f.clean(''))
+ self.assertEqual([], f.clean(None))
+ self.assertEqual(['1'], f.clean([1]))
+ self.assertEqual(['1'], f.clean(['1']))
+ self.assertEqual(['1', '2'], f.clean(['1', '2']))
+ self.assertEqual(['1', '2'], f.clean([1, '2']))
+ self.assertEqual(['1', '2'], f.clean((1, '2')))
+ self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello')
+ self.assertEqual([], f.clean([]))
+ self.assertEqual([], f.clean(()))
+ self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, ['3'])
+
+ def test_multiplechoicefield_3(self):
+ f = MultipleChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')])
+ self.assertEqual(['1'], f.clean([1]))
+ self.assertEqual(['1'], f.clean(['1']))
+ self.assertEqual(['1', '5'], f.clean([1, 5]))
+ self.assertEqual(['1', '5'], f.clean([1, '5']))
+ self.assertEqual(['1', '5'], f.clean(['1', 5]))
+ self.assertEqual(['1', '5'], f.clean(['1', '5']))
+ self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['6'])
+ self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['1','6'])
+
+ def test_multiplechoicefield_changed(self):
+ f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two'), ('3', 'Three')])
+ self.assertFalse(f._has_changed(None, None))
+ self.assertFalse(f._has_changed([], None))
+ self.assertTrue(f._has_changed(None, ['1']))
+ self.assertFalse(f._has_changed([1, 2], ['1', '2']))
+ self.assertFalse(f._has_changed([2, 1], ['1', '2']))
+ self.assertTrue(f._has_changed([1, 2], ['1']))
+ self.assertTrue(f._has_changed([1, 2], ['1', '3']))
+
+ # TypedMultipleChoiceField ############################################################
+ # TypedMultipleChoiceField is just like MultipleChoiceField, except that coerced types
+ # will be returned:
+
+ def test_typedmultiplechoicefield_1(self):
+ f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
+ self.assertEqual([1], f.clean(['1']))
+ self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, ['2'])
+
+ def test_typedmultiplechoicefield_2(self):
+ # Different coercion, same validation.
+ f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float)
+ self.assertEqual([1.0], f.clean(['1']))
+
+ def test_typedmultiplechoicefield_3(self):
+ # This can also cause weirdness: be careful (bool(-1) == True, remember)
+ f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool)
+ self.assertEqual([True], f.clean(['-1']))
+
+ def test_typedmultiplechoicefield_4(self):
+ f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
+ self.assertEqual([1, -1], f.clean(['1','-1']))
+ self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, ['1','2'])
+
+ def test_typedmultiplechoicefield_5(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 = TypedMultipleChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int)
+ self.assertRaisesMessage(ValidationError, "'Select a valid choice. B is not one of the available choices.'", f.clean, ['B'])
+ # Required fields require values
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, [])
+
+ def test_typedmultiplechoicefield_6(self):
+ # Non-required fields aren't required
+ f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False)
+ self.assertEqual([], f.clean([]))
+
+ def test_typedmultiplechoicefield_7(self):
+ # If you want cleaning an empty value to return a different type, tell the field
+ f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None)
+ self.assertEqual(None, f.clean([]))
+
+ # ComboField ##################################################################
+
+ def test_combofield_1(self):
+ f = ComboField(fields=[CharField(max_length=20), EmailField()])
+ self.assertEqual('test@example.com', f.clean('test@example.com'))
+ self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", f.clean, 'longemailaddress@example.com')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'not an email')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+
+ def test_combofield_2(self):
+ f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False)
+ self.assertEqual('test@example.com', f.clean('test@example.com'))
+ self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", f.clean, 'longemailaddress@example.com')
+ self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'not an email')
+ self.assertEqual('', f.clean(''))
+ self.assertEqual('', f.clean(None))
+
+ # FilePathField ###############################################################
+
+ def test_filepathfield_1(self):
+ path = os.path.abspath(upath(forms.__file__))
+ path = os.path.dirname(path) + '/'
+ self.assertTrue(fix_os_paths(path).endswith('/django/forms/'))
+
+ def test_filepathfield_2(self):
+ path = upath(forms.__file__)
+ path = os.path.dirname(os.path.abspath(path)) + '/'
+ f = FilePathField(path=path)
+ f.choices = [p for p in f.choices if p[0].endswith('.py')]
+ f.choices.sort()
+ expected = [
+ ('/django/forms/__init__.py', '__init__.py'),
+ ('/django/forms/fields.py', 'fields.py'),
+ ('/django/forms/forms.py', 'forms.py'),
+ ('/django/forms/formsets.py', 'formsets.py'),
+ ('/django/forms/models.py', 'models.py'),
+ ('/django/forms/util.py', 'util.py'),
+ ('/django/forms/widgets.py', 'widgets.py')
+ ]
+ for exp, got in zip(expected, fix_os_paths(f.choices)):
+ self.assertEqual(exp[1], got[1])
+ self.assertTrue(got[0].endswith(exp[0]))
+ self.assertRaisesMessage(ValidationError, "'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_3(self):
+ path = upath(forms.__file__)
+ path = os.path.dirname(os.path.abspath(path)) + '/'
+ f = FilePathField(path=path, match='^.*?\.py$')
+ f.choices.sort()
+ expected = [
+ ('/django/forms/__init__.py', '__init__.py'),
+ ('/django/forms/fields.py', 'fields.py'),
+ ('/django/forms/forms.py', 'forms.py'),
+ ('/django/forms/formsets.py', 'formsets.py'),
+ ('/django/forms/models.py', 'models.py'),
+ ('/django/forms/util.py', 'util.py'),
+ ('/django/forms/widgets.py', 'widgets.py')
+ ]
+ for exp, got in zip(expected, fix_os_paths(f.choices)):
+ self.assertEqual(exp[1], got[1])
+ self.assertTrue(got[0].endswith(exp[0]))
+
+ def test_filepathfield_4(self):
+ path = os.path.abspath(upath(forms.__file__))
+ path = os.path.dirname(path) + '/'
+ f = FilePathField(path=path, recursive=True, match='^.*?\.py$')
+ f.choices.sort()
+ expected = [
+ ('/django/forms/__init__.py', '__init__.py'),
+ ('/django/forms/extras/__init__.py', 'extras/__init__.py'),
+ ('/django/forms/extras/widgets.py', 'extras/widgets.py'),
+ ('/django/forms/fields.py', 'fields.py'),
+ ('/django/forms/forms.py', 'forms.py'),
+ ('/django/forms/formsets.py', 'formsets.py'),
+ ('/django/forms/models.py', 'models.py'),
+ ('/django/forms/util.py', 'util.py'),
+ ('/django/forms/widgets.py', 'widgets.py')
+ ]
+ for exp, got in zip(expected, fix_os_paths(f.choices)):
+ self.assertEqual(exp[1], got[1])
+ self.assertTrue(got[0].endswith(exp[0]))
+
+ def test_filepathfield_folders(self):
+ path = os.path.dirname(upath(__file__)) + '/filepath_test_files/'
+ f = FilePathField(path=path, allow_folders=True, allow_files=False)
+ f.choices.sort()
+ expected = [
+ ('/tests/forms_tests/tests/filepath_test_files/directory', 'directory'),
+ ]
+ for exp, got in zip(expected, fix_os_paths(f.choices)):
+ self.assertEqual(exp[1], got[1])
+ self.assertTrue(got[0].endswith(exp[0]))
+
+ f = FilePathField(path=path, allow_folders=True, allow_files=True)
+ f.choices.sort()
+ expected = [
+ ('/tests/forms_tests/tests/filepath_test_files/.dot-file', '.dot-file'),
+ ('/tests/forms_tests/tests/filepath_test_files/directory', 'directory'),
+ ('/tests/forms_tests/tests/filepath_test_files/fake-image.jpg', 'fake-image.jpg'),
+ ('/tests/forms_tests/tests/filepath_test_files/real-text-file.txt', 'real-text-file.txt'),
+ ]
+
+ actual = fix_os_paths(f.choices)
+ self.assertEqual(len(expected), len(actual))
+ for exp, got in zip(expected, actual):
+ self.assertEqual(exp[1], got[1])
+ self.assertTrue(got[0].endswith(exp[0]))
+
+
+ # SplitDateTimeField ##########################################################
+
+ def test_splitdatetimefield_1(self):
+ from django.forms.widgets import SplitDateTimeWidget
+ f = SplitDateTimeField()
+ assert isinstance(f.widget, SplitDateTimeWidget)
+ self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)]))
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
+ self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
+ self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello')
+ six.assertRaisesRegex(self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there'])
+ self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there'])
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30'])
+
+ 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']))
+ self.assertEqual(None, f.clean(None))
+ self.assertEqual(None, f.clean(''))
+ self.assertEqual(None, f.clean(['']))
+ self.assertEqual(None, f.clean(['', '']))
+ self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello')
+ six.assertRaisesRegex(self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there'])
+ self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there'])
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30'])
+ self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', ''])
+ self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10'])
+ self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['', '07:30'])
+
+ def test_splitdatetimefield_changed(self):
+ f = SplitDateTimeField(input_date_formats=['%d/%m/%Y'])
+ self.assertTrue(f._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['2008-05-06', '12:40:00']))
+ self.assertFalse(f._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['06/05/2008', '12:40']))
+ self.assertTrue(f._has_changed(datetime.datetime(2008, 5, 6, 12, 40, 00), ['06/05/2008', '12:41']))
diff --git a/tests/forms_tests/tests/filepath_test_files/.dot-file b/tests/forms_tests/tests/filepath_test_files/.dot-file
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/tests/forms_tests/tests/filepath_test_files/.dot-file
diff --git a/tests/forms_tests/tests/filepath_test_files/directory/.keep b/tests/forms_tests/tests/filepath_test_files/directory/.keep
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/tests/forms_tests/tests/filepath_test_files/directory/.keep
diff --git a/tests/forms_tests/tests/filepath_test_files/fake-image.jpg b/tests/forms_tests/tests/filepath_test_files/fake-image.jpg
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/tests/forms_tests/tests/filepath_test_files/fake-image.jpg
diff --git a/tests/forms_tests/tests/filepath_test_files/real-text-file.txt b/tests/forms_tests/tests/filepath_test_files/real-text-file.txt
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/tests/forms_tests/tests/filepath_test_files/real-text-file.txt
diff --git a/tests/forms_tests/tests/forms.py b/tests/forms_tests/tests/forms.py
new file mode 100644
index 0000000000..f856e30d33
--- /dev/null
+++ b/tests/forms_tests/tests/forms.py
@@ -0,0 +1,1799 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+import datetime
+
+from django.core.files.uploadedfile import SimpleUploadedFile
+from django.forms import *
+from django.http import QueryDict
+from django.template import Template, Context
+from django.test import TestCase
+from django.test.utils import str_prefix
+from django.utils.datastructures import MultiValueDict, MergeDict
+from django.utils.safestring import mark_safe
+from django.utils import six
+
+
+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': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'})
+
+ self.assertTrue(p.is_bound)
+ self.assertEqual(p.errors, {})
+ self.assertTrue(p.is_valid())
+ self.assertHTMLEqual(p.errors.as_ul(), '')
+ self.assertEqual(p.errors.as_text(), '')
+ self.assertEqual(p.cleaned_data["first_name"], 'John')
+ self.assertEqual(p.cleaned_data["last_name"], 'Lennon')
+ self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
+ self.assertHTMLEqual(str(p['first_name']), '<input type="text" name="first_name" value="John" id="id_first_name" />')
+ self.assertHTMLEqual(str(p['last_name']), '<input type="text" name="last_name" value="Lennon" id="id_last_name" />')
+ self.assertHTMLEqual(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.assertHTMLEqual('\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', 'John'],
+ ['Last name', 'Lennon'],
+ ['Birthday', '1940-10-9']
+ ])
+ self.assertHTMLEqual(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'], ['This field is required.'])
+ self.assertEqual(p.errors['last_name'], ['This field is required.'])
+ self.assertEqual(p.errors['birthday'], ['This field is required.'])
+ self.assertFalse(p.is_valid())
+ self.assertEqual(p.cleaned_data, {})
+ self.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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': 'John', 'last_name': '\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'})
+ self.assertHTMLEqual(p.as_table(), '<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.assertHTMLEqual(p.as_ul(), '<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.assertHTMLEqual(p.as_p(), '<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': 'Lennon'})
+ self.assertEqual(p.errors['first_name'], ['This field is required.'])
+ self.assertEqual(p.errors['birthday'], ['This field is required.'])
+ self.assertFalse(p.is_valid())
+ self.assertDictEqual(p.errors, {'birthday': ['This field is required.'], 'first_name': ['This field is required.']})
+ self.assertEqual(p.cleaned_data, {'last_name': 'Lennon'})
+ self.assertEqual(p['first_name'].errors, ['This field is required.'])
+ self.assertHTMLEqual(p['first_name'].errors.as_ul(), '<ul class="errorlist"><li>This field is required.</li></ul>')
+ self.assertEqual(p['first_name'].errors.as_text(), '* This field is required.')
+
+ p = Person()
+ self.assertHTMLEqual(str(p['first_name']), '<input type="text" name="first_name" id="id_first_name" />')
+ self.assertHTMLEqual(str(p['last_name']), '<input type="text" name="last_name" id="id_last_name" />')
+ self.assertHTMLEqual(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': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9', 'extra1': 'hello', 'extra2': 'hello'}
+ p = Person(data)
+ self.assertTrue(p.is_valid())
+ self.assertEqual(p.cleaned_data['first_name'], 'John')
+ self.assertEqual(p.cleaned_data['last_name'], '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': 'John', 'last_name': 'Lennon'}
+ f = OptionalPersonForm(data)
+ self.assertTrue(f.is_valid())
+ self.assertEqual(f.cleaned_data['nick_name'], '')
+ self.assertEqual(f.cleaned_data['first_name'], 'John')
+ self.assertEqual(f.cleaned_data['last_name'], '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': 'John', 'last_name': 'Lennon'}
+ f = OptionalPersonForm(data)
+ self.assertTrue(f.is_valid())
+ self.assertEqual(f.cleaned_data['birth_date'], None)
+ self.assertEqual(f.cleaned_data['first_name'], 'John')
+ self.assertEqual(f.cleaned_data['last_name'], '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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(str(f['email']), '<input type="email" name="email" />')
+ self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
+
+ f = SignupForm({'email': 'test@example.com', 'get_spam': True}, auto_id=False)
+ self.assertHTMLEqual(str(f['email']), '<input type="email" name="email" value="test@example.com" />')
+ self.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
+
+ f = SignupForm({'email': 'test@example.com', 'get_spam': 'false'}, auto_id=False)
+ self.assertHTMLEqual(str(f['get_spam']), '<input type="checkbox" name="get_spam" />')
+
+ # A value of '0' should be interpreted as a True value (#16820)
+ f = SignupForm({'email': 'test@example.com', 'get_spam': '0'})
+ self.assertTrue(f.is_valid())
+ self.assertTrue(f.cleaned_data.get('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.assertHTMLEqual(str(f['subject']), '<input type="text" name="subject" />')
+ self.assertHTMLEqual(str(f['message']), '<textarea name="message" rows="10" cols="40"></textarea>')
+
+ # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output
+ # widget type:
+ self.assertHTMLEqual(f['subject'].as_textarea(), '<textarea name="subject" rows="10" cols="40"></textarea>')
+ self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" />')
+ self.assertHTMLEqual(f['message'].as_hidden(), '<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.assertHTMLEqual(str(f['message']), '<textarea name="message" rows="80" cols="20"></textarea>')
+
+ # Instance-level attrs are *not* carried over to as_textarea(), as_text() and
+ # as_hidden():
+ self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" />')
+ f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False)
+ self.assertHTMLEqual(f['subject'].as_textarea(), '<textarea rows="10" cols="40" name="subject">Hello</textarea>')
+ self.assertHTMLEqual(f['message'].as_text(), '<input type="text" name="message" value="I love you." />')
+ self.assertHTMLEqual(f['message'].as_hidden(), '<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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(str(f['language']), """<select name="language">
+</select>""")
+ f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')]
+ self.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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_form_with_iterable_boundfield(self):
+ class BeatleForm(Form):
+ name = ChoiceField(choices=[('john', 'John'), ('paul', 'Paul'), ('george', 'George'), ('ringo', 'Ringo')], widget=RadioSelect)
+
+ f = BeatleForm(auto_id=False)
+ self.assertHTMLEqual('\n'.join([str(bf) for bf in f['name']]), """<label><input type="radio" name="name" value="john" /> John</label>
+<label><input type="radio" name="name" value="paul" /> Paul</label>
+<label><input type="radio" name="name" value="george" /> George</label>
+<label><input type="radio" name="name" value="ringo" /> Ringo</label>""")
+ self.assertHTMLEqual('\n'.join(['<div>%s</div>' % bf for bf in f['name']]), """<div><label><input type="radio" name="name" value="john" /> John</label></div>
+<div><label><input type="radio" name="name" value="paul" /> Paul</label></div>
+<div><label><input type="radio" name="name" value="george" /> George</label></div>
+<div><label><input type="radio" name="name" value="ringo" /> Ringo</label></div>""")
+
+ def test_form_with_noniterable_boundfield(self):
+ # You can iterate over any BoundField, not just those with widget=RadioSelect.
+ class BeatleForm(Form):
+ name = CharField()
+
+ f = BeatleForm(auto_id=False)
+ self.assertHTMLEqual('\n'.join([str(bf) for bf in f['name']]), '<input type="text" name="name" />')
+
+ def test_forms_with_multiple_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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(str(f['name']), '<input type="text" name="name" value="Yesterday" />')
+ self.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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'], ['This field is required.'])
+ f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False)
+ self.assertEqual(f.errors, {})
+ self.assertEqual(f.cleaned_data['composers'], ['J'])
+ self.assertEqual(f.cleaned_data['name'], 'Yesterday')
+ f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False)
+ self.assertEqual(f.errors, {})
+ self.assertEqual(f.cleaned_data['composers'], ['J', 'P'])
+ self.assertEqual(f.cleaned_data['name'], '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.assertHTMLEqual(f.as_table(), """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td><ul class="errorlist"><li>Something&#39;s wrong with &#39;Nothing to escape&#39;</li></ul><input type="text" name="special_name" value="Nothing to escape" /></td></tr>
+<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.assertHTMLEqual(f.as_table(), """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td><ul class="errorlist"><li>Something&#39;s wrong with &#39;Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;&#39;</li></ul><input type="text" name="special_name" value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;" /></td></tr>
+<tr><th><em>Special</em> Field:</th><td><ul class="errorlist"><li>'<b><i>Do not escape</i></b>' is a safe string</li></ul><input type="text" name="special_safe_name" value="&lt;i&gt;Do not escape&lt;/i&gt;" /></td></tr>""")
+
+ 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('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'], ['This field is required.'])
+ self.assertEqual(f.errors['password1'], ['This field is required.'])
+ self.assertEqual(f.errors['password2'], ['This field is required.'])
+ f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
+ self.assertEqual(f.errors['password2'], ['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'], 'adrian')
+ self.assertEqual(f.cleaned_data['password1'], 'foo')
+ self.assertEqual(f.cleaned_data['password2'], '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('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.assertHTMLEqual(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'], ['This field is required.'])
+ self.assertEqual(f.errors['password1'], ['This field is required.'])
+ self.assertEqual(f.errors['password2'], ['This field is required.'])
+ f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
+ self.assertEqual(f.errors['__all__'], ['Please make sure your passwords match.'])
+ self.assertHTMLEqual(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.assertHTMLEqual(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'], 'adrian')
+ self.assertEqual(f.cleaned_data['password1'], 'foo')
+ self.assertEqual(f.cleaned_data['password2'], '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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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))
+
+ # Similarly, choices do not persist from one Form instance to the next.
+ # Refs #15127.
+ class Person(Form):
+ first_name = CharField(required=False)
+ last_name = CharField(required=False)
+ gender = ChoiceField(choices=(('f', 'Female'), ('m', 'Male')))
+
+ def __init__(self, allow_unspec_gender=False, *args, **kwargs):
+ super(Person, self).__init__(*args, **kwargs)
+
+ if allow_unspec_gender:
+ self.fields['gender'].choices += (('u', 'Unspecified'),)
+
+ f = Person()
+ self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')])
+ f = Person(allow_unspec_gender=True)
+ self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male'), ('u', 'Unspecified')])
+ f = Person()
+ self.assertEqual(f['gender'].field.choices, [('f', 'Female'), ('m', 'Male')])
+
+ def test_validators_independence(self):
+ """ Test that we are able to modify a form field validators list without polluting
+ other forms """
+ from django.core.validators import MaxValueValidator
+ class MyForm(Form):
+ myfield = CharField(max_length=25)
+
+ f1 = MyForm()
+ f2 = MyForm()
+
+ f1.fields['myfield'].validators[0] = MaxValueValidator(12)
+ self.assertFalse(f1.fields['myfield'].validators[0] == f2.fields['myfield'].validators[0])
+
+ 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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(p.as_table(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
+ self.assertHTMLEqual(p.as_ul(), '<input type="hidden" name="foo" /><input type="hidden" name="bar" />')
+ self.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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='\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111')
+
+ p = UserRegistration(auto_id=False)
+ self.assertHTMLEqual(p.as_ul(), '<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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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='\u2192')
+ self.assertHTMLEqual(f.as_ul(), '<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.assertHTMLEqual(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.assertHTMLEqual(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': ''}, auto_id=False)
+ self.assertHTMLEqual(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': 'foo'}, auto_id=False)
+ self.assertHTMLEqual(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'], ['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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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': ''}, initial={'username': 'django'}, auto_id=False)
+ self.assertHTMLEqual(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': 'foo'}, initial={'username': 'django'}, auto_id=False)
+ self.assertHTMLEqual(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'], ['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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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': ''}, initial={'username': initial_django}, auto_id=False)
+ self.assertHTMLEqual(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': 'foo', 'options':['f','b']}, initial={'username': initial_django}, auto_id=False)
+ self.assertHTMLEqual(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'], ['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.assertHTMLEqual(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.assertHTMLEqual(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_boundfield_values(self):
+ # It's possible to get to the value which would be used for rendering
+ # the widget for a field by using the BoundField's value method.
+
+ class UserRegistration(Form):
+ username = CharField(max_length=10, initial='djangonaut')
+ password = CharField(widget=PasswordInput)
+
+ unbound = UserRegistration()
+ bound = UserRegistration({'password': 'foo'})
+ self.assertEqual(bound['username'].value(), None)
+ self.assertEqual(unbound['username'].value(), 'djangonaut')
+ self.assertEqual(bound['password'].value(), 'foo')
+ self.assertEqual(unbound['password'].value(), None)
+
+ 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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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': 'foo'}, auto_id=False)
+ self.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(p.as_ul(), '<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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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': 'John',
+ 'person1-last_name': 'Lennon',
+ 'person1-birthday': '1940-10-9'
+ }
+ p = Person(data, prefix='person1')
+ self.assertHTMLEqual(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.assertHTMLEqual(str(p['first_name']), '<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" />')
+ self.assertHTMLEqual(str(p['last_name']), '<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" />')
+ self.assertHTMLEqual(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'], 'John')
+ self.assertEqual(p.cleaned_data['last_name'], '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': '',
+ 'person1-last_name': '',
+ 'person1-birthday': ''
+ }
+ p = Person(data, prefix='person1')
+ self.assertEqual(p.errors['first_name'], ['This field is required.'])
+ self.assertEqual(p.errors['last_name'], ['This field is required.'])
+ self.assertEqual(p.errors['birthday'], ['This field is required.'])
+ self.assertEqual(p['first_name'].errors, ['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': 'John',
+ 'last_name': 'Lennon',
+ 'birthday': '1940-10-9'
+ }
+ p = Person(data, prefix='person1')
+ self.assertEqual(p.errors['first_name'], ['This field is required.'])
+ self.assertEqual(p.errors['last_name'], ['This field is required.'])
+ self.assertEqual(p.errors['birthday'], ['This field is required.'])
+
+ # With prefixes, a single data dictionary can hold data for multiple instances
+ # of the same form.
+ data = {
+ 'person1-first_name': 'John',
+ 'person1-last_name': 'Lennon',
+ 'person1-birthday': '1940-10-9',
+ 'person2-first_name': 'Jim',
+ 'person2-last_name': 'Morrison',
+ 'person2-birthday': '1943-12-8'
+ }
+ p1 = Person(data, prefix='person1')
+ self.assertTrue(p1.is_valid())
+ self.assertEqual(p1.cleaned_data['first_name'], 'John')
+ self.assertEqual(p1.cleaned_data['last_name'], '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'], 'Jim')
+ self.assertEqual(p2.cleaned_data['last_name'], '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.assertHTMLEqual(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': 'John',
+ 'foo-prefix-last_name': 'Lennon',
+ 'foo-prefix-birthday': '1940-10-9'
+ }
+ p = Person(data, prefix='foo')
+ self.assertTrue(p.is_valid())
+ self.assertEqual(p.cleaned_data['first_name'], 'John')
+ self.assertEqual(p.cleaned_data['last_name'], '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': 'Joe'}, auto_id=False)
+ self.assertHTMLEqual(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': 'Joe', 'is_cool': '1'}, auto_id=False)
+ self.assertHTMLEqual(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': 'Joe', 'is_cool': '2'}, auto_id=False)
+ self.assertHTMLEqual(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': 'Joe', 'is_cool': '3'}, auto_id=False)
+ self.assertHTMLEqual(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': 'Joe', 'is_cool': True}, auto_id=False)
+ self.assertHTMLEqual(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': 'Joe', 'is_cool': False}, auto_id=False)
+ self.assertHTMLEqual(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.assertHTMLEqual(f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1" /></td></tr>')
+
+ f = FileForm(data={}, files={}, auto_id=False)
+ self.assertHTMLEqual(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', b'')}, auto_id=False)
+ self.assertHTMLEqual(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.assertHTMLEqual(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', b'some content')}, auto_id=False)
+ self.assertHTMLEqual(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', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, auto_id=False)
+ self.assertHTMLEqual(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('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' % sorted(six.iteritems(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.assertHTMLEqual(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.assertHTMLEqual(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'}),
+ str_prefix("VALID: [('password1', %(_)s'secret'), ('password2', %(_)s'secret'), ('username', %(_)s'adrian')]"))
+
+ 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('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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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&#39;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)})), '')
+
+ # 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'}))
+
+ expected_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>',
+ ]
+ self.assertEqual(len(form_output), len(expected_form_output))
+ for i in range(len(form_output)):
+ self.assertHTMLEqual(form_output[i], expected_form_output[i])
+
+ # 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.assertHTMLEqual(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.assertHTMLEqual(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': ['This field is required.'], 'artist': ['This field is required.']})
+ self.assertEqual(form.cleaned_data, {})
+
+ # 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': ['This field is required.']})
+ self.assertEqual(form.cleaned_data, {'artist': 'The Doors'})
+
+ # 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.assertHTMLEqual(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.assertHTMLEqual(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="email" 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="number" name="age" id="id_age" /></li>""")
+
+ self.assertHTMLEqual(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="email" 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="number" name="age" id="id_age" /></p>""")
+
+ self.assertHTMLEqual(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="email" 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="number" 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.assertHTMLEqual(form.as_ul(), '<input type="hidden" name="happened_at_0" id="id_happened_at_0" /><input type="hidden" name="happened_at_1" id="id_happened_at_1" />')
+
+ def test_multivalue_field_validation(self):
+ def bad_names(value):
+ if value == 'bad value':
+ raise ValidationError('bad value not allowed')
+
+ class NameField(MultiValueField):
+ def __init__(self, fields=(), *args, **kwargs):
+ fields = (CharField(label='First name', max_length=10),
+ CharField(label='Last name', max_length=10))
+ super(NameField, self).__init__(fields=fields, *args, **kwargs)
+
+ def compress(self, data_list):
+ return ' '.join(data_list)
+
+ class NameForm(Form):
+ name = NameField(validators=[bad_names])
+
+ form = NameForm(data={'name' : ['bad', 'value']})
+ form.full_clean()
+ self.assertFalse(form.is_valid())
+ self.assertEqual(form.errors, {'name': ['bad value not allowed']})
+ form = NameForm(data={'name' : ['should be overly', 'long for the field names']})
+ self.assertFalse(form.is_valid())
+ self.assertEqual(form.errors, {'name': ['Ensure this value has at most 10 characters (it has 16).',
+ 'Ensure this value has at most 10 characters (it has 24).']})
+ form = NameForm(data={'name' : ['fname', 'lname']})
+ self.assertTrue(form.is_valid())
+ self.assertEqual(form.cleaned_data, {'name' : 'fname lname'})
diff --git a/tests/forms_tests/tests/formsets.py b/tests/forms_tests/tests/formsets.py
new file mode 100644
index 0000000000..2bef0c5c33
--- /dev/null
+++ b/tests/forms_tests/tests/formsets.py
@@ -0,0 +1,1055 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.forms import (CharField, DateField, FileField, Form, IntegerField,
+ ValidationError, formsets)
+from django.forms.formsets import BaseFormSet, formset_factory
+from django.forms.util import ErrorList
+from django.test 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'])
+
+
+class EmptyFsetWontValidate(BaseFormSet):
+ def clean(self):
+ raise ValidationError("Clean method called")
+
+
+# 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.assertHTMLEqual(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" value="1000" />
+<tr><th>Choice:</th><td><input type="text" name="choices-0-choice" /></td></tr>
+<tr><th>Votes:</th><td><input type="number" 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': 'Calexico'}])
+
+ # If a FormSet was not passed any data, its is_valid and has_changed
+ # methods should return False.
+ formset = ChoiceFormSet()
+ self.assertFalse(formset.is_valid())
+ self.assertFalse(formset.has_changed())
+
+ 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': ['This field is required.']}])
+
+ def test_formset_has_changed(self):
+ # FormSet instances has_changed method will be True if any data is
+ # passed to his forms, even if the formset didn't validate
+ 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': '',
+ 'choices-0-votes': '',
+ }
+ blank_formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertFalse(blank_formset.has_changed())
+
+ # invalid formset test
+ data['choices-0-choice'] = 'Calexico'
+ invalid_formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertFalse(invalid_formset.is_valid())
+ self.assertTrue(invalid_formset.has_changed())
+
+ # valid formset test
+ data['choices-0-votes'] = '100'
+ valid_formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertTrue(valid_formset.is_valid())
+ self.assertTrue(valid_formset.has_changed())
+
+ 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': '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.assertHTMLEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li>
+<li>Votes: <input type="number" name="choices-0-votes" value="100" /></li>
+<li>Choice: <input type="text" name="choices-1-choice" /></li>
+<li>Votes: <input type="number" 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': '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': ['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': ['This field is required.'], 'choice': ['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.assertHTMLEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" /></li>
+<li>Votes: <input type="number" name="choices-0-votes" /></li>
+<li>Choice: <input type="text" name="choices-1-choice" /></li>
+<li>Votes: <input type="number" name="choices-1-votes" /></li>
+<li>Choice: <input type="text" name="choices-2-choice" /></li>
+<li>Votes: <input type="number" 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': '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': ['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': '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.assertHTMLEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li>
+<li>Votes: <input type="number" name="choices-0-votes" value="100" /></li>
+<li>Choice: <input type="text" name="choices-1-choice" /></li>
+<li>Votes: <input type="number" name="choices-1-votes" /></li>
+<li>Choice: <input type="text" name="choices-2-choice" /></li>
+<li>Votes: <input type="number" name="choices-2-votes" /></li>
+<li>Choice: <input type="text" name="choices-3-choice" /></li>
+<li>Votes: <input type="number" 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.assertHTMLEqual(formset.empty_form.as_ul(), """<li>Choice: <input type="text" name="choices-__prefix__-choice" /></li>
+<li>Votes: <input type="number" 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': 'Calexico', 'votes': 100}, {'choice': '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.assertHTMLEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li>
+<li>Votes: <input type="number" 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="number" 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="number" 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': 'Calexico'}, {'votes': 900, 'DELETE': True, 'choice': 'Fergie'}, {}])
+ self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'choice': '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': '', 'form-0-DELETE': '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': 'Calexico', 'votes': 100}, {'choice': '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.assertHTMLEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li>
+<li>Votes: <input type="number" name="choices-0-votes" value="100" /></li>
+<li>Order: <input type="number" name="choices-0-ORDER" value="1" /></li>
+<li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li>
+<li>Votes: <input type="number" name="choices-1-votes" value="900" /></li>
+<li>Order: <input type="number" name="choices-1-ORDER" value="2" /></li>
+<li>Choice: <input type="text" name="choices-2-choice" /></li>
+<li>Votes: <input type="number" name="choices-2-votes" /></li>
+<li>Order: <input type="number" 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': 'The Decemberists'},
+ {'votes': 100, 'ORDER': 1, 'choice': 'Calexico'},
+ {'votes': 900, 'ORDER': 2, 'choice': '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': 'Calexico'},
+ {'votes': 900, 'ORDER': 2, 'choice': 'Fergie'},
+ {'votes': 500, 'ORDER': None, 'choice': 'The Decemberists'},
+ {'votes': 50, 'ORDER': None, 'choice': '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': 'Calexico', 'votes': 100},
+ {'choice': 'Fergie', 'votes': 900},
+ {'choice': '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.assertHTMLEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li>
+<li>Votes: <input type="number" name="choices-0-votes" value="100" /></li>
+<li>Order: <input type="number" 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="number" name="choices-1-votes" value="900" /></li>
+<li>Order: <input type="number" 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="number" name="choices-2-votes" value="500" /></li>
+<li>Order: <input type="number" 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="number" name="choices-3-votes" /></li>
+<li>Order: <input type="number" 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': 'The Decemberists'},
+ {'votes': 100, 'DELETE': False, 'ORDER': 1, 'choice': 'Calexico'},
+ ])
+ self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': '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': '',
+ 'form-0-DELETE': '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 a high default value, leaving the
+ # 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.assertHTMLEqual('\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.assertHTMLEqual('\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.assertHTMLEqual('\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 a high default value, leaving the
+ # number of forms only controlled by the value 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.assertHTMLEqual('\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.assertHTMLEqual('\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.assertHTMLEqual('\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')
+
+ data = {
+ 'form-TOTAL_FORMS': '2',
+ 'form-INITIAL_FORMS': '0',
+ 'form-MAX_NUM_FORMS': '0',
+ }
+ formset = FavoriteDrinksFormSet(data=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(), ['You may only specify a drink once.'])
+
+ def test_formset_iteration(self):
+ # Regression tests for #16455 -- formset instances are iterable
+ ChoiceFormset = formset_factory(Choice, extra=3)
+ formset = ChoiceFormset()
+
+ # confirm iterated formset yields formset.forms
+ forms = list(formset)
+ self.assertEqual(forms, formset.forms)
+ self.assertEqual(len(formset), len(forms))
+
+ # confirm indexing of formset
+ self.assertEqual(formset[0], forms[0])
+ try:
+ formset[3]
+ self.fail('Requesting an invalid formset index should raise an exception')
+ except IndexError:
+ pass
+
+ # Formets can override the default iteration order
+ class BaseReverseFormSet(BaseFormSet):
+ def __iter__(self):
+ return reversed(self.forms)
+
+ def __getitem__(self, idx):
+ return super(BaseReverseFormSet, self).__getitem__(len(self) - idx - 1)
+
+ ReverseChoiceFormset = formset_factory(Choice, BaseReverseFormSet, extra=3)
+ reverse_formset = ReverseChoiceFormset()
+
+ # confirm that __iter__ modifies rendering order
+ # compare forms from "reverse" formset with forms from original formset
+ self.assertEqual(str(reverse_formset[0]), str(forms[-1]))
+ self.assertEqual(str(reverse_formset[1]), str(forms[-2]))
+ self.assertEqual(len(reverse_formset), len(forms))
+
+ def test_formset_nonzero(self):
+ """
+ Formsets with no forms should still evaluate as true.
+ Regression test for #15722
+ """
+ ChoiceFormset = formset_factory(Choice, extra=0)
+ formset = ChoiceFormset()
+ self.assertEqual(len(formset.forms), 0)
+ self.assertTrue(formset)
+
+
+ def test_formset_error_class(self):
+ # Regression tests for #16479 -- formsets form use ErrorList instead of supplied error_class
+ class CustomErrorList(ErrorList):
+ pass
+
+ formset = FavoriteDrinksFormSet(error_class=CustomErrorList)
+ self.assertEqual(formset.forms[0].error_class, CustomErrorList)
+
+ def test_formset_calls_forms_is_valid(self):
+ # Regression tests for #18574 -- make sure formsets call
+ # is_valid() on each form.
+
+ class AnotherChoice(Choice):
+ def is_valid(self):
+ self.is_valid_called = True
+ return super(AnotherChoice, self).is_valid()
+
+ AnotherChoiceFormSet = formset_factory(AnotherChoice)
+ data = {
+ 'choices-TOTAL_FORMS': '1', # number of forms rendered
+ 'choices-INITIAL_FORMS': '0', # number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': 'Calexico',
+ 'choices-0-votes': '100',
+ }
+ formset = AnotherChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertTrue(formset.is_valid())
+ self.assertTrue(all([form.is_valid_called for form in formset.forms]))
+
+ def test_hard_limit_on_instantiated_forms(self):
+ """A formset has a hard limit on the number of forms instantiated."""
+ # reduce the default limit of 1000 temporarily for testing
+ _old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM
+ try:
+ formsets.DEFAULT_MAX_NUM = 3
+ ChoiceFormSet = formset_factory(Choice)
+ # someone fiddles with the mgmt form data...
+ formset = ChoiceFormSet(
+ {
+ 'choices-TOTAL_FORMS': '4',
+ 'choices-INITIAL_FORMS': '0',
+ 'choices-MAX_NUM_FORMS': '4',
+ 'choices-0-choice': 'Zero',
+ 'choices-0-votes': '0',
+ 'choices-1-choice': 'One',
+ 'choices-1-votes': '1',
+ 'choices-2-choice': 'Two',
+ 'choices-2-votes': '2',
+ 'choices-3-choice': 'Three',
+ 'choices-3-votes': '3',
+ },
+ prefix='choices',
+ )
+ # But we still only instantiate 3 forms
+ self.assertEqual(len(formset.forms), 3)
+ finally:
+ formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM
+
+ def test_increase_hard_limit(self):
+ """Can increase the built-in forms limit via a higher max_num."""
+ # reduce the default limit of 1000 temporarily for testing
+ _old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM
+ try:
+ formsets.DEFAULT_MAX_NUM = 3
+ # for this form, we want a limit of 4
+ ChoiceFormSet = formset_factory(Choice, max_num=4)
+ formset = ChoiceFormSet(
+ {
+ 'choices-TOTAL_FORMS': '4',
+ 'choices-INITIAL_FORMS': '0',
+ 'choices-MAX_NUM_FORMS': '4',
+ 'choices-0-choice': 'Zero',
+ 'choices-0-votes': '0',
+ 'choices-1-choice': 'One',
+ 'choices-1-votes': '1',
+ 'choices-2-choice': 'Two',
+ 'choices-2-votes': '2',
+ 'choices-3-choice': 'Three',
+ 'choices-3-votes': '3',
+ },
+ prefix='choices',
+ )
+ # This time four forms are instantiated
+ self.assertEqual(len(formset.forms), 4)
+ finally:
+ formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM
+
+
+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.assertHTMLEqual(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="number" name="choices-0-votes" value="100" /></td></tr>""")
+
+ def test_as_p(self):
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertHTMLEqual(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="number" name="choices-0-votes" value="100" /></p>""")
+
+ def test_as_ul(self):
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertHTMLEqual(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="number" name="choices-0-votes" value="100" /></li>""")
+
+
+# Regression test for #11418 #################################################
+class ArticleForm(Form):
+ title = CharField()
+ pub_date = DateField()
+
+ArticleFormSet = formset_factory(ArticleForm)
+
+class TestIsBoundBehavior(TestCase):
+ def test_no_data_raises_validation_error(self):
+ self.assertRaises(ValidationError, ArticleFormSet, {})
+
+ def test_with_management_data_attrs_work_fine(self):
+ data = {
+ 'form-TOTAL_FORMS': '1',
+ 'form-INITIAL_FORMS': '0',
+ }
+ formset = ArticleFormSet(data)
+ self.assertEqual(0, formset.initial_form_count())
+ self.assertEqual(1, formset.total_form_count())
+ self.assertTrue(formset.is_bound)
+ self.assertTrue(formset.forms[0].is_bound)
+ self.assertTrue(formset.is_valid())
+ self.assertTrue(formset.forms[0].is_valid())
+ self.assertEqual([{}], formset.cleaned_data)
+
+
+ def test_form_errors_are_cought_by_formset(self):
+ data = {
+ 'form-TOTAL_FORMS': '2',
+ 'form-INITIAL_FORMS': '0',
+ 'form-0-title': 'Test',
+ 'form-0-pub_date': '1904-06-16',
+ 'form-1-title': 'Test',
+ 'form-1-pub_date': '', # <-- this date is missing but required
+ }
+ formset = ArticleFormSet(data)
+ self.assertFalse(formset.is_valid())
+ self.assertEqual([{}, {'pub_date': ['This field is required.']}], formset.errors)
+
+ def test_empty_forms_are_unbound(self):
+ data = {
+ 'form-TOTAL_FORMS': '1',
+ 'form-INITIAL_FORMS': '0',
+ 'form-0-title': 'Test',
+ 'form-0-pub_date': '1904-06-16',
+ }
+ unbound_formset = ArticleFormSet()
+ bound_formset = ArticleFormSet(data)
+
+ empty_forms = []
+
+ empty_forms.append(unbound_formset.empty_form)
+ empty_forms.append(bound_formset.empty_form)
+
+ # Empty forms should be unbound
+ self.assertFalse(empty_forms[0].is_bound)
+ self.assertFalse(empty_forms[1].is_bound)
+
+ # The empty forms should be equal.
+ self.assertHTMLEqual(empty_forms[0].as_p(), empty_forms[1].as_p())
+
+class TestEmptyFormSet(TestCase):
+ def test_empty_formset_is_valid(self):
+ """Test that an empty formset still calls clean()"""
+ EmptyFsetWontValidateFormset = formset_factory(FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate)
+ formset = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS':'0', 'form-TOTAL_FORMS':'0'},prefix="form")
+ formset2 = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS':'0', 'form-TOTAL_FORMS':'1', 'form-0-name':'bah' },prefix="form")
+ self.assertFalse(formset.is_valid())
+ self.assertFalse(formset2.is_valid())
+
+ def test_empty_formset_media(self):
+ """Make sure media is available on empty formset, refs #19545"""
+ class MediaForm(Form):
+ class Media:
+ js = ('some-file.js',)
+ self.assertIn('some-file.js', str(formset_factory(MediaForm, extra=0)().media))
+
+ def test_empty_formset_is_multipart(self):
+ """Make sure `is_multipart()` works with empty formset, refs #19545"""
+ class FileForm(Form):
+ file = FileField()
+ self.assertTrue(formset_factory(FileForm, extra=0)().is_multipart())
diff --git a/tests/forms_tests/tests/input_formats.py b/tests/forms_tests/tests/input_formats.py
new file mode 100644
index 0000000000..7a305dbc2b
--- /dev/null
+++ b/tests/forms_tests/tests/input_formats.py
@@ -0,0 +1,861 @@
+from datetime import time, date, datetime
+
+from django import forms
+from django.test.utils import override_settings
+from django.utils.translation import activate, deactivate
+from django.test import SimpleTestCase
+
+
+@override_settings(TIME_INPUT_FORMATS=["%I:%M:%S %p", "%I:%M %p"], USE_L10N=True)
+class LocalizedTimeTests(SimpleTestCase):
+ def setUp(self):
+ # nl/formats.py has customized TIME_INPUT_FORMATS
+ activate('nl')
+
+ def tearDown(self):
+ deactivate()
+
+ def test_timeField(self):
+ "TimeFields can parse dates in the default format"
+ f = forms.TimeField()
+ # Parse a time in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM')
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('13:30:05')
+ self.assertEqual(result, time(13,30,5))
+
+ # Check that the parsed result does a round trip
+ text = f.widget._format_value(result)
+ self.assertEqual(text, '13:30:05')
+
+ # Parse a time in a valid, but non-default format, get a parsed result
+ result = f.clean('13:30')
+ self.assertEqual(result, time(13,30,0))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "13:30:00")
+
+ def test_localized_timeField(self):
+ "Localized TimeFields act as unlocalized widgets"
+ f = forms.TimeField(localize=True)
+ # Parse a time in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM')
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('13:30:05')
+ self.assertEqual(result, time(13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, '13:30:05')
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('13:30')
+ self.assertEqual(result, time(13,30,0))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "13:30:00")
+
+ def test_timeField_with_inputformat(self):
+ "TimeFields with manually specified input formats can accept those formats"
+ f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"])
+ # Parse a time in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM')
+ self.assertRaises(forms.ValidationError, f.clean, '13:30:05')
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('13.30.05')
+ self.assertEqual(result, time(13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "13:30:05")
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('13.30')
+ self.assertEqual(result, time(13,30,0))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "13:30:00")
+
+ def test_localized_timeField_with_inputformat(self):
+ "Localized TimeFields with manually specified input formats can accept those formats"
+ f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True)
+ # Parse a time in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM')
+ self.assertRaises(forms.ValidationError, f.clean, '13:30:05')
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('13.30.05')
+ self.assertEqual(result, time(13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "13:30:05")
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('13.30')
+ self.assertEqual(result, time(13,30,0))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "13:30:00")
+
+
+@override_settings(TIME_INPUT_FORMATS=["%I:%M:%S %p", "%I:%M %p"])
+class CustomTimeInputFormatsTests(SimpleTestCase):
+ def test_timeField(self):
+ "TimeFields can parse dates in the default format"
+ f = forms.TimeField()
+ # Parse a time in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '13:30:05')
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('1:30:05 PM')
+ self.assertEqual(result, time(13,30,5))
+
+ # Check that the parsed result does a round trip
+ text = f.widget._format_value(result)
+ self.assertEqual(text, '01:30:05 PM')
+
+ # Parse a time in a valid, but non-default format, get a parsed result
+ result = f.clean('1:30 PM')
+ self.assertEqual(result, time(13,30,0))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "01:30:00 PM")
+
+ def test_localized_timeField(self):
+ "Localized TimeFields act as unlocalized widgets"
+ f = forms.TimeField(localize=True)
+ # Parse a time in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '13:30:05')
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('1:30:05 PM')
+ self.assertEqual(result, time(13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, '01:30:05 PM')
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('01:30 PM')
+ self.assertEqual(result, time(13,30,0))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "01:30:00 PM")
+
+ def test_timeField_with_inputformat(self):
+ "TimeFields with manually specified input formats can accept those formats"
+ f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"])
+ # Parse a time in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM')
+ self.assertRaises(forms.ValidationError, f.clean, '13:30:05')
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('13.30.05')
+ self.assertEqual(result, time(13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "01:30:05 PM")
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('13.30')
+ self.assertEqual(result, time(13,30,0))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "01:30:00 PM")
+
+ def test_localized_timeField_with_inputformat(self):
+ "Localized TimeFields with manually specified input formats can accept those formats"
+ f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True)
+ # Parse a time in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM')
+ self.assertRaises(forms.ValidationError, f.clean, '13:30:05')
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('13.30.05')
+ self.assertEqual(result, time(13,30,5))
+
+ # # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "01:30:05 PM")
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('13.30')
+ self.assertEqual(result, time(13,30,0))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "01:30:00 PM")
+
+
+class SimpleTimeFormatTests(SimpleTestCase):
+ def test_timeField(self):
+ "TimeFields can parse dates in the default format"
+ f = forms.TimeField()
+ # Parse a time in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM')
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('13:30:05')
+ self.assertEqual(result, time(13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "13:30:05")
+
+ # Parse a time in a valid, but non-default format, get a parsed result
+ result = f.clean('13:30')
+ self.assertEqual(result, time(13,30,0))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "13:30:00")
+
+ def test_localized_timeField(self):
+ "Localized TimeFields in a non-localized environment act as unlocalized widgets"
+ f = forms.TimeField()
+ # Parse a time in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM')
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('13:30:05')
+ self.assertEqual(result, time(13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "13:30:05")
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('13:30')
+ self.assertEqual(result, time(13,30,0))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "13:30:00")
+
+ def test_timeField_with_inputformat(self):
+ "TimeFields with manually specified input formats can accept those formats"
+ f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"])
+ # Parse a time in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '13:30:05')
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('1:30:05 PM')
+ self.assertEqual(result, time(13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "13:30:05")
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('1:30 PM')
+ self.assertEqual(result, time(13,30,0))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "13:30:00")
+
+ def test_localized_timeField_with_inputformat(self):
+ "Localized TimeFields with manually specified input formats can accept those formats"
+ f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"], localize=True)
+ # Parse a time in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '13:30:05')
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('1:30:05 PM')
+ self.assertEqual(result, time(13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "13:30:05")
+
+ # Parse a time in a valid format, get a parsed result
+ result = f.clean('1:30 PM')
+ self.assertEqual(result, time(13,30,0))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "13:30:00")
+
+
+@override_settings(DATE_INPUT_FORMATS=["%d/%m/%Y", "%d-%m-%Y"], USE_L10N=True)
+class LocalizedDateTests(SimpleTestCase):
+ def setUp(self):
+ activate('de')
+
+ def tearDown(self):
+ deactivate()
+
+ def test_dateField(self):
+ "DateFields can parse dates in the default format"
+ f = forms.DateField()
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '21/12/2010')
+
+ # ISO formats are accepted, even if not specified in formats.py
+ self.assertEqual(f.clean('2010-12-21'), date(2010,12,21))
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('21.12.2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip
+ text = f.widget._format_value(result)
+ self.assertEqual(text, '21.12.2010')
+
+ # Parse a date in a valid, but non-default format, get a parsed result
+ result = f.clean('21.12.10')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010")
+
+ def test_localized_dateField(self):
+ "Localized DateFields act as unlocalized widgets"
+ f = forms.DateField(localize=True)
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '21/12/2010')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('21.12.2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, '21.12.2010')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('21.12.10')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010")
+
+ def test_dateField_with_inputformat(self):
+ "DateFields with manually specified input formats can accept those formats"
+ f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"])
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21')
+ self.assertRaises(forms.ValidationError, f.clean, '21/12/2010')
+ self.assertRaises(forms.ValidationError, f.clean, '21.12.2010')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('12.21.2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010")
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('12-21-2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010")
+
+ def test_localized_dateField_with_inputformat(self):
+ "Localized DateFields with manually specified input formats can accept those formats"
+ f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True)
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21')
+ self.assertRaises(forms.ValidationError, f.clean, '21/12/2010')
+ self.assertRaises(forms.ValidationError, f.clean, '21.12.2010')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('12.21.2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010")
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('12-21-2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010")
+
+
+@override_settings(DATE_INPUT_FORMATS=["%d.%m.%Y", "%d-%m-%Y"])
+class CustomDateInputFormatsTests(SimpleTestCase):
+ def test_dateField(self):
+ "DateFields can parse dates in the default format"
+ f = forms.DateField()
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('21.12.2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip
+ text = f.widget._format_value(result)
+ self.assertEqual(text, '21.12.2010')
+
+ # Parse a date in a valid, but non-default format, get a parsed result
+ result = f.clean('21-12-2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010")
+
+ def test_localized_dateField(self):
+ "Localized DateFields act as unlocalized widgets"
+ f = forms.DateField(localize=True)
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('21.12.2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, '21.12.2010')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('21-12-2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010")
+
+ def test_dateField_with_inputformat(self):
+ "DateFields with manually specified input formats can accept those formats"
+ f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"])
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '21.12.2010')
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('12.21.2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010")
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('12-21-2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010")
+
+ def test_localized_dateField_with_inputformat(self):
+ "Localized DateFields with manually specified input formats can accept those formats"
+ f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True)
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '21.12.2010')
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('12.21.2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010")
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('12-21-2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010")
+
+class SimpleDateFormatTests(SimpleTestCase):
+ def test_dateField(self):
+ "DateFields can parse dates in the default format"
+ f = forms.DateField()
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '21.12.2010')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('2010-12-21')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21")
+
+ # Parse a date in a valid, but non-default format, get a parsed result
+ result = f.clean('12/21/2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21")
+
+ def test_localized_dateField(self):
+ "Localized DateFields in a non-localized environment act as unlocalized widgets"
+ f = forms.DateField()
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '21.12.2010')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('2010-12-21')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21")
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('12/21/2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21")
+
+ def test_dateField_with_inputformat(self):
+ "DateFields with manually specified input formats can accept those formats"
+ f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"])
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('21.12.2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21")
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('21-12-2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21")
+
+ def test_localized_dateField_with_inputformat(self):
+ "Localized DateFields with manually specified input formats can accept those formats"
+ f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"], localize=True)
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('21.12.2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21")
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('21-12-2010')
+ self.assertEqual(result, date(2010,12,21))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21")
+
+
+@override_settings(DATETIME_INPUT_FORMATS=["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"], USE_L10N=True)
+class LocalizedDateTimeTests(SimpleTestCase):
+ def setUp(self):
+ activate('de')
+
+ def tearDown(self):
+ deactivate()
+
+ def test_dateTimeField(self):
+ "DateTimeFields can parse dates in the default format"
+ f = forms.DateTimeField()
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010')
+
+ # ISO formats are accepted, even if not specified in formats.py
+ self.assertEqual(f.clean('2010-12-21 13:30:05'), datetime(2010,12,21,13,30,5))
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('21.12.2010 13:30:05')
+ self.assertEqual(result, datetime(2010,12,21,13,30,5))
+
+ # Check that the parsed result does a round trip
+ text = f.widget._format_value(result)
+ self.assertEqual(text, '21.12.2010 13:30:05')
+
+ # Parse a date in a valid, but non-default format, get a parsed result
+ result = f.clean('21.12.2010 13:30')
+ self.assertEqual(result, datetime(2010,12,21,13,30))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010 13:30:00")
+
+ def test_localized_dateTimeField(self):
+ "Localized DateTimeFields act as unlocalized widgets"
+ f = forms.DateTimeField(localize=True)
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('21.12.2010 13:30:05')
+ self.assertEqual(result, datetime(2010,12,21,13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, '21.12.2010 13:30:05')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('21.12.2010 13:30')
+ self.assertEqual(result, datetime(2010,12,21,13,30))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010 13:30:00")
+
+ def test_dateTimeField_with_inputformat(self):
+ "DateTimeFields with manually specified input formats can accept those formats"
+ f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"])
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05 13:30:05')
+ self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010')
+ self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('13.30.05 12.21.2010')
+ self.assertEqual(result, datetime(2010,12,21,13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010 13:30:05")
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('13.30 12-21-2010')
+ self.assertEqual(result, datetime(2010,12,21,13,30))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010 13:30:00")
+
+ def test_localized_dateTimeField_with_inputformat(self):
+ "Localized DateTimeFields with manually specified input formats can accept those formats"
+ f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"], localize=True)
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05')
+ self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010')
+ self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('13.30.05 12.21.2010')
+ self.assertEqual(result, datetime(2010,12,21,13,30,5))
+
+ # # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010 13:30:05")
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('13.30 12-21-2010')
+ self.assertEqual(result, datetime(2010,12,21,13,30))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "21.12.2010 13:30:00")
+
+
+@override_settings(DATETIME_INPUT_FORMATS=["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"])
+class CustomDateTimeInputFormatsTests(SimpleTestCase):
+ def test_dateTimeField(self):
+ "DateTimeFields can parse dates in the default format"
+ f = forms.DateTimeField()
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('1:30:05 PM 21/12/2010')
+ self.assertEqual(result, datetime(2010,12,21,13,30,5))
+
+ # Check that the parsed result does a round trip
+ text = f.widget._format_value(result)
+ self.assertEqual(text, '01:30:05 PM 21/12/2010')
+
+ # Parse a date in a valid, but non-default format, get a parsed result
+ result = f.clean('1:30 PM 21-12-2010')
+ self.assertEqual(result, datetime(2010,12,21,13,30))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "01:30:00 PM 21/12/2010")
+
+ def test_localized_dateTimeField(self):
+ "Localized DateTimeFields act as unlocalized widgets"
+ f = forms.DateTimeField(localize=True)
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('1:30:05 PM 21/12/2010')
+ self.assertEqual(result, datetime(2010,12,21,13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, '01:30:05 PM 21/12/2010')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('1:30 PM 21-12-2010')
+ self.assertEqual(result, datetime(2010,12,21,13,30))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "01:30:00 PM 21/12/2010")
+
+ def test_dateTimeField_with_inputformat(self):
+ "DateTimeFields with manually specified input formats can accept those formats"
+ f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"])
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010')
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('12.21.2010 13:30:05')
+ self.assertEqual(result, datetime(2010,12,21,13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "01:30:05 PM 21/12/2010")
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('12-21-2010 13:30')
+ self.assertEqual(result, datetime(2010,12,21,13,30))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "01:30:00 PM 21/12/2010")
+
+ def test_localized_dateTimeField_with_inputformat(self):
+ "Localized DateTimeFields with manually specified input formats can accept those formats"
+ f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"], localize=True)
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010')
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('12.21.2010 13:30:05')
+ self.assertEqual(result, datetime(2010,12,21,13,30,5))
+
+ # # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "01:30:05 PM 21/12/2010")
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('12-21-2010 13:30')
+ self.assertEqual(result, datetime(2010,12,21,13,30))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "01:30:00 PM 21/12/2010")
+
+class SimpleDateTimeFormatTests(SimpleTestCase):
+ def test_dateTimeField(self):
+ "DateTimeFields can parse dates in the default format"
+ f = forms.DateTimeField()
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('2010-12-21 13:30:05')
+ self.assertEqual(result, datetime(2010,12,21,13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21 13:30:05")
+
+ # Parse a date in a valid, but non-default format, get a parsed result
+ result = f.clean('12/21/2010 13:30:05')
+ self.assertEqual(result, datetime(2010,12,21,13,30,5))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21 13:30:05")
+
+ def test_localized_dateTimeField(self):
+ "Localized DateTimeFields in a non-localized environment act as unlocalized widgets"
+ f = forms.DateTimeField()
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('2010-12-21 13:30:05')
+ self.assertEqual(result, datetime(2010,12,21,13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21 13:30:05")
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('12/21/2010 13:30:05')
+ self.assertEqual(result, datetime(2010,12,21,13,30,5))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21 13:30:05")
+
+ def test_dateTimeField_with_inputformat(self):
+ "DateTimeFields with manually specified input formats can accept those formats"
+ f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"])
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('1:30:05 PM 21.12.2010')
+ self.assertEqual(result, datetime(2010,12,21,13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21 13:30:05")
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('1:30 PM 21-12-2010')
+ self.assertEqual(result, datetime(2010,12,21,13,30))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21 13:30:00")
+
+ def test_localized_dateTimeField_with_inputformat(self):
+ "Localized DateTimeFields with manually specified input formats can accept those formats"
+ f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"], localize=True)
+ # Parse a date in an unaccepted format; get an error
+ self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05')
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('1:30:05 PM 21.12.2010')
+ self.assertEqual(result, datetime(2010,12,21,13,30,5))
+
+ # Check that the parsed result does a round trip to the same format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21 13:30:05")
+
+ # Parse a date in a valid format, get a parsed result
+ result = f.clean('1:30 PM 21-12-2010')
+ self.assertEqual(result, datetime(2010,12,21,13,30))
+
+ # Check that the parsed result does a round trip to default format
+ text = f.widget._format_value(result)
+ self.assertEqual(text, "2010-12-21 13:30:00")
diff --git a/tests/forms_tests/tests/media.py b/tests/forms_tests/tests/media.py
new file mode 100644
index 0000000000..c492a1e539
--- /dev/null
+++ b/tests/forms_tests/tests/media.py
@@ -0,0 +1,907 @@
+# -*- coding: utf-8 -*-
+from django.forms import TextInput, Media, TextInput, CharField, Form, MultiWidget
+from django.template import Template, Context
+from django.test import TestCase
+from django.test.utils import override_settings
+
+
+@override_settings(
+ STATIC_URL=None,
+ MEDIA_URL='http://media.example.com/media/',
+)
+class FormsMediaTestCase(TestCase):
+ """Tests for the media handling on widgets and forms"""
+
+ 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
+ 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" />""")
+
+
+@override_settings(
+ STATIC_URL='http://media.example.com/static/',
+ MEDIA_URL='http://media.example.com/media/',
+)
+class StaticFormsMediaTestCase(TestCase):
+ """Tests for the media handling on widgets and forms"""
+
+ 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/static/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/static/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/static/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/static/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/static/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/static/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/static/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/static/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/static/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/static/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/static/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/static/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/static/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/static/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/static/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/static/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
+ 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/static/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/forms_tests/tests/models.py b/tests/forms_tests/tests/models.py
new file mode 100644
index 0000000000..be75643b28
--- /dev/null
+++ b/tests/forms_tests/tests/models.py
@@ -0,0 +1,218 @@
+# -*- coding: utf-8 -*-
+from __future__ import absolute_import, unicode_literals
+
+import datetime
+
+from django.core.files.uploadedfile import SimpleUploadedFile
+from django.db import models
+from django.forms import Form, ModelForm, FileField, ModelChoiceField
+from django.forms.models import ModelFormMetaclass
+from django.test import TestCase
+from django.utils import six
+
+from ..models import (ChoiceOptionModel, ChoiceFieldModel, FileModel, Group,
+ BoundaryModel, Defaults, OptionalMultiChoiceModel)
+
+
+class ChoiceFieldForm(ModelForm):
+ class Meta:
+ model = ChoiceFieldModel
+
+
+class OptionalMultiChoiceModelForm(ModelForm):
+ class Meta:
+ model = OptionalMultiChoiceModel
+
+
+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):
+ # only one query is required to pull the model from DB
+ with self.assertNumQueries(1):
+ field = ModelChoiceField(Group.objects.order_by('-name'))
+ self.assertEqual('a', field.clean(self.groups[0].pk).name)
+
+
+class TestTicket14567(TestCase):
+ """
+ Check that the return values of ModelMultipleChoiceFields are QuerySets
+ """
+ def test_empty_queryset_return(self):
+ "If a model's ManyToManyField has blank=True and is saved with no data, a queryset is returned."
+ form = OptionalMultiChoiceModelForm({'multi_choice_optional': '', 'multi_choice': ['1']})
+ self.assertTrue(form.is_valid())
+ # Check that the empty value is a QuerySet
+ self.assertTrue(isinstance(form.cleaned_data['multi_choice_optional'], models.query.QuerySet))
+ # While we're at it, test whether a QuerySet is returned if there *is* a value.
+ self.assertTrue(isinstance(form.cleaned_data['multi_choice'], models.query.QuerySet))
+
+
+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.assertEqual(len(choices), 1)
+ self.assertEqual(choices[0], (option.pk, six.text_type(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.assertHTMLEqual(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.assertHTMLEqual(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', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, 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, '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, '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='instance value', def_date=datetime.date(1969, 4, 4), value=12)
+ instance_form = DefaultsForm(instance=foo_instance)
+ self.assertEqual(instance_form.initial['name'], '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': 'Hello', 'value': 99, 'def_date': datetime.date(1999, 3, 2)})
+ self.assertTrue(f.is_valid())
+ self.assertEqual(f.cleaned_data['name'], 'Hello')
+ obj = f.save()
+ self.assertEqual(obj.name, 'class default value')
+ self.assertEqual(obj.value, 99)
+ self.assertEqual(obj.def_date, datetime.date(1999, 3, 2))
+
+class RelatedModelFormTests(TestCase):
+ def test_invalid_loading_order(self):
+ """
+ Test for issue 10405
+ """
+ class A(models.Model):
+ ref = models.ForeignKey("B")
+
+ class Meta:
+ model=A
+
+ self.assertRaises(ValueError, ModelFormMetaclass, str('Form'), (ModelForm,), {'Meta': Meta})
+
+ class B(models.Model):
+ pass
+
+ def test_valid_loading_order(self):
+ """
+ Test for issue 10405
+ """
+ class A(models.Model):
+ ref = models.ForeignKey("B")
+
+ class B(models.Model):
+ pass
+
+ class Meta:
+ model=A
+
+ self.assertTrue(issubclass(ModelFormMetaclass(str('Form'), (ModelForm,), {'Meta': Meta}), ModelForm))
diff --git a/tests/forms_tests/tests/regressions.py b/tests/forms_tests/tests/regressions.py
new file mode 100644
index 0000000000..ecee92402e
--- /dev/null
+++ b/tests/forms_tests/tests/regressions.py
@@ -0,0 +1,150 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from warnings import catch_warnings
+
+from django.forms import *
+from django.test import TestCase
+from django.utils.translation import ugettext_lazy, override
+
+from forms_tests.models import Cheese
+
+
+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.assertHTMLEqual(TestForm(auto_id=False).as_p(), '<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.assertHTMLEqual(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)
+ with override('de'):
+ self.assertHTMLEqual(f.as_p(), '<p><label for="id_username">Benutzername:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>')
+ with override('pl', deactivate=True):
+ self.assertHTMLEqual(f.as_p(), '<p><label for="id_username">Nazwa u\u017cytkownika:</label> <input id="id_username" type="text" name="username" maxlength="10" /></p>')
+
+ 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.assertHTMLEqual(f['field_1'].label_tag(), '<label for="id_field_1">field_1</label>')
+ self.assertHTMLEqual(f['field_2'].label_tag(), '<label for="field_2_id">field_2</label>')
+
+ # Unicode decoding problems...
+ GENDERS = (('\xc5', 'En tied\xe4'), ('\xf8', 'Mies'), ('\xdf', 'Nainen'))
+
+ class SomeForm(Form):
+ somechoice = ChoiceField(choices=GENDERS, widget=RadioSelect(), label='\xc5\xf8\xdf')
+
+ f = SomeForm()
+ self.assertHTMLEqual(f.as_p(), '<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 = ((b'\xd0\xbc\xd0\xb5\xd1\x81.', b'\xd0\xbc\xd0\xb5\xd1\x81.'),
+ (b'\xd1\x88\xd1\x82.', b'\xd1\x88\xd1\x82.'))
+ f = ChoiceField(choices=UNITS)
+ self.assertEqual(f.clean('\u0448\u0442.'), '\u0448\u0442.')
+ with catch_warnings(record=True):
+ # Ignore UnicodeWarning
+ self.assertEqual(f.clean(b'\xd1\x88\xd1\x82.'), '\u0448\u0442.')
+
+ # Translated error messages used to be buggy.
+ with override('ru'):
+ f = SomeForm({})
+ self.assertHTMLEqual(f.as_p(), '<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>')
+
+ # 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': '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.assertHTMLEqual(f.as_p(), '<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.assertHTMLEqual(f.as_table(), '<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.assertHTMLEqual(t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>')
+
+ class SomeForm(Form):
+ field = MultipleChoiceField(choices=[('one', 'One')])
+
+ f = SomeForm({'field': ['<script>']})
+ self.assertHTMLEqual(t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>Select a valid choice. &lt;script&gt; is not one of the available choices.</li></ul></li></ul>')
+
+ from forms_tests.models import ChoiceModel
+
+ class SomeForm(Form):
+ field = ModelMultipleChoiceField(ChoiceModel.objects.all())
+
+ f = SomeForm({'field': ['<script>']})
+ self.assertHTMLEqual(t.render(Context({'form': f})), '<ul class="errorlist"><li>field<ul class="errorlist"><li>&quot;&lt;script&gt;&quot; is not a valid value for a primary key.</li></ul></li></ul>')
+
+ def test_regression_14234(self):
+ """
+ Re-cleaning an instance that was added via a ModelForm should not raise
+ a pk uniqueness error.
+
+ """
+ class CheeseForm(ModelForm):
+ class Meta:
+ model = Cheese
+
+ form = CheeseForm({
+ 'name': 'Brie',
+ })
+
+ self.assertTrue(form.is_valid())
+
+ obj = form.save()
+ obj.name = 'Camembert'
+ obj.full_clean()
diff --git a/tests/forms_tests/tests/util.py b/tests/forms_tests/tests/util.py
new file mode 100644
index 0000000000..c2d213ae23
--- /dev/null
+++ b/tests/forms_tests/tests/util.py
@@ -0,0 +1,67 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.core.exceptions import ValidationError
+from django.forms.util import flatatt, ErrorDict, ErrorList
+from django.test import TestCase
+from django.utils.safestring import mark_safe
+from django.utils import six
+from django.utils.translation import ugettext_lazy
+from django.utils.encoding import python_2_unicode_compatible
+
+
+class FormsUtilTestCase(TestCase):
+ # Tests for forms/util.py module.
+
+ def test_flatatt(self):
+ ###########
+ # flatatt #
+ ###########
+
+ self.assertEqual(flatatt({'id': "header"}), ' id="header"')
+ self.assertEqual(flatatt({'class': "news", 'title': "Read this"}), ' class="news" title="Read this"')
+ self.assertEqual(flatatt({}), '')
+
+ def test_validation_error(self):
+ ###################
+ # ValidationError #
+ ###################
+
+ # Can take a string.
+ self.assertHTMLEqual(str(ErrorList(ValidationError("There was an error.").messages)),
+ '<ul class="errorlist"><li>There was an error.</li></ul>')
+
+ # Can take a unicode string.
+ self.assertHTMLEqual(six.text_type(ErrorList(ValidationError("Not \u03C0.").messages)),
+ '<ul class="errorlist"><li>Not π.</li></ul>')
+
+ # Can take a lazy string.
+ self.assertHTMLEqual(str(ErrorList(ValidationError(ugettext_lazy("Error.")).messages)),
+ '<ul class="errorlist"><li>Error.</li></ul>')
+
+ # Can take a list.
+ self.assertHTMLEqual(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.assertHTMLEqual(str(ErrorList(ValidationError(["First error.", "Not \u03C0.", ugettext_lazy("Error.")]).messages)),
+ '<ul class="errorlist"><li>First error.</li><li>Not π.</li><li>Error.</li></ul>')
+
+ @python_2_unicode_compatible
+ class VeryBadError:
+ def __str__(self): return "A very bad error."
+
+ # Can take a non-string.
+ self.assertHTMLEqual(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.assertHTMLEqual(str(ErrorList([example])),
+ '<ul class="errorlist"><li>Example of link: &lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>')
+ self.assertHTMLEqual(str(ErrorList([mark_safe(example)])),
+ '<ul class="errorlist"><li>Example of link: <a href="http://www.example.com/">example</a></li></ul>')
+ self.assertHTMLEqual(str(ErrorDict({'name': example})),
+ '<ul class="errorlist"><li>nameExample of link: &lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>')
+ self.assertHTMLEqual(str(ErrorDict({'name': mark_safe(example)})),
+ '<ul class="errorlist"><li>nameExample of link: <a href="http://www.example.com/">example</a></li></ul>')
diff --git a/tests/forms_tests/tests/validators.py b/tests/forms_tests/tests/validators.py
new file mode 100644
index 0000000000..a4cb324815
--- /dev/null
+++ b/tests/forms_tests/tests/validators.py
@@ -0,0 +1,16 @@
+from django import forms
+from django.core import validators
+from django.core.exceptions import ValidationError
+from django.utils.unittest import TestCase
+
+
+class TestFieldWithValidators(TestCase):
+ def test_all_errors_get_reported(self):
+ field = forms.CharField(
+ validators=[validators.validate_integer, validators.validate_email]
+ )
+ self.assertRaises(ValidationError, field.clean, 'not int nor mail')
+ try:
+ field.clean('not int nor mail')
+ except ValidationError as e:
+ self.assertEqual(2, len(e.messages))
diff --git a/tests/forms_tests/tests/widgets.py b/tests/forms_tests/tests/widgets.py
new file mode 100644
index 0000000000..00e45b6b02
--- /dev/null
+++ b/tests/forms_tests/tests/widgets.py
@@ -0,0 +1,1124 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+import copy
+import datetime
+
+from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase
+from django.core.files.uploadedfile import SimpleUploadedFile
+from django.core.urlresolvers import reverse
+from django.forms import *
+from django.forms.widgets import RadioFieldRenderer
+from django.utils import formats
+from django.utils.safestring import mark_safe
+from django.utils import six
+from django.utils.translation import activate, deactivate
+from django.test import TestCase
+from django.test.utils import override_settings
+from django.utils.encoding import python_2_unicode_compatible
+
+from ..models import Article
+
+
+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.assertHTMLEqual(w.render('email', ''), '<input type="text" name="email" />')
+ self.assertHTMLEqual(w.render('email', None), '<input type="text" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com'), '<input type="text" name="email" value="test@example.com" />')
+ self.assertHTMLEqual(w.render('email', 'some "quoted" & ampersanded value'), '<input type="text" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), '<input type="text" name="email" value="test@example.com" class="fun" />')
+
+ self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), '<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', 'type': 'email'})
+ self.assertHTMLEqual(w.render('email', ''), '<input type="email" class="fun" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'foo@example.com'), '<input type="email" 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.assertHTMLEqual(w.render('email', '', attrs={'class': 'special'}), '<input type="text" class="special" name="email" />')
+
+ # 'attrs' can be safe-strings if needed)
+ w = TextInput(attrs={'onBlur': mark_safe("function('foo')")})
+ self.assertHTMLEqual(w.render('email', ''), '<input onBlur="function(\'foo\')" type="text" name="email" />')
+
+ def test_passwordinput(self):
+ w = PasswordInput()
+ self.assertHTMLEqual(w.render('email', ''), '<input type="password" name="email" />')
+ self.assertHTMLEqual(w.render('email', None), '<input type="password" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'secret'), '<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.assertHTMLEqual(w.render('email', ''), '<input type="password" name="email" />')
+ self.assertHTMLEqual(w.render('email', None), '<input type="password" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com'), '<input type="password" name="email" value="test@example.com" />')
+ self.assertHTMLEqual(w.render('email', 'some "quoted" & ampersanded value'), '<input type="password" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), '<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.assertHTMLEqual(w.render('email', ''), '<input type="password" class="fun" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'foo@example.com'), '<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.assertHTMLEqual(w.render('email', '', attrs={'class': 'special'}), '<input type="password" class="special" name="email" />')
+
+ self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), '<input type="password" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />')
+
+ def test_hiddeninput(self):
+ w = HiddenInput()
+ self.assertHTMLEqual(w.render('email', ''), '<input type="hidden" name="email" />')
+ self.assertHTMLEqual(w.render('email', None), '<input type="hidden" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com'), '<input type="hidden" name="email" value="test@example.com" />')
+ self.assertHTMLEqual(w.render('email', 'some "quoted" & ampersanded value'), '<input type="hidden" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), '<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.assertHTMLEqual(w.render('email', ''), '<input type="hidden" class="fun" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'foo@example.com'), '<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.assertHTMLEqual(w.render('email', '', attrs={'class': 'special'}), '<input type="hidden" class="special" name="email" />')
+
+ self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), '<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.assertHTMLEqual(w.render('email', '', attrs={'class': 'special'}), '<input type="hidden" class="special" name="email" />')
+
+ # Boolean values are rendered to their string forms ("True" and "False").
+ w = HiddenInput()
+ self.assertHTMLEqual(w.render('get_spam', False), '<input type="hidden" name="get_spam" value="False" />')
+ self.assertHTMLEqual(w.render('get_spam', True), '<input type="hidden" name="get_spam" value="True" />')
+
+ def test_multiplehiddeninput(self):
+ w = MultipleHiddenInput()
+ self.assertHTMLEqual(w.render('email', []), '')
+ self.assertHTMLEqual(w.render('email', None), '')
+ self.assertHTMLEqual(w.render('email', ['test@example.com']), '<input type="hidden" name="email" value="test@example.com" />')
+ self.assertHTMLEqual(w.render('email', ['some "quoted" & ampersanded value']), '<input type="hidden" name="email" value="some &quot;quoted&quot; &amp; ampersanded value" />')
+ self.assertHTMLEqual(w.render('email', ['test@example.com', 'foo@example.com']), '<input type="hidden" name="email" value="test@example.com" />\n<input type="hidden" name="email" value="foo@example.com" />')
+ self.assertHTMLEqual(w.render('email', ['test@example.com'], attrs={'class': 'fun'}), '<input type="hidden" name="email" value="test@example.com" class="fun" />')
+ self.assertHTMLEqual(w.render('email', ['test@example.com', 'foo@example.com'], attrs={'class': 'fun'}), '<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.assertHTMLEqual(w.render('email', []), '')
+ self.assertHTMLEqual(w.render('email', ['foo@example.com']), '<input type="hidden" class="fun" value="foo@example.com" name="email" />')
+ self.assertHTMLEqual(w.render('email', ['foo@example.com', 'test@example.com']), '<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.assertHTMLEqual(w.render('email', ['foo@example.com'], attrs={'class': 'special'}), '<input type="hidden" class="special" value="foo@example.com" name="email" />')
+
+ self.assertHTMLEqual(w.render('email', ['ŠĐĆŽćžšđ'], attrs={'class': 'fun'}), '<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.assertHTMLEqual(w.render('email', ['foo@example.com'], attrs={'class': 'special'}), '<input type="hidden" class="special" value="foo@example.com" name="email" />')
+
+ # Each input gets a separate ID.
+ w = MultipleHiddenInput()
+ self.assertHTMLEqual(w.render('letters', list('abc'), attrs={'id': 'hideme'}), '<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.assertHTMLEqual(w.render('email', ''), '<input type="file" name="email" />')
+ self.assertHTMLEqual(w.render('email', None), '<input type="file" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com'), '<input type="file" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'some "quoted" & ampersanded value'), '<input type="file" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'test@example.com', attrs={'class': 'fun'}), '<input type="file" name="email" class="fun" />')
+
+ # You can also pass 'attrs' to the constructor:
+ w = FileInput(attrs={'class': 'fun'})
+ self.assertHTMLEqual(w.render('email', ''), '<input type="file" class="fun" name="email" />')
+ self.assertHTMLEqual(w.render('email', 'foo@example.com'), '<input type="file" class="fun" name="email" />')
+
+ self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), '<input type="file" class="fun" name="email" />')
+
+ def test_textarea(self):
+ w = Textarea()
+ self.assertHTMLEqual(w.render('msg', ''), '<textarea rows="10" cols="40" name="msg"></textarea>')
+ self.assertHTMLEqual(w.render('msg', None), '<textarea rows="10" cols="40" name="msg"></textarea>')
+ self.assertHTMLEqual(w.render('msg', 'value'), '<textarea rows="10" cols="40" name="msg">value</textarea>')
+ self.assertHTMLEqual(w.render('msg', 'some "quoted" & ampersanded value'), '<textarea rows="10" cols="40" name="msg">some &quot;quoted&quot; &amp; ampersanded value</textarea>')
+ self.assertHTMLEqual(w.render('msg', mark_safe('pre &quot;quoted&quot; value')), '<textarea rows="10" cols="40" name="msg">pre &quot;quoted&quot; value</textarea>')
+ self.assertHTMLEqual(w.render('msg', 'value', attrs={'class': 'pretty', 'rows': 20}), '<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.assertHTMLEqual(w.render('msg', ''), '<textarea rows="10" cols="40" name="msg" class="pretty"></textarea>')
+ self.assertHTMLEqual(w.render('msg', 'example'), '<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.assertHTMLEqual(w.render('msg', '', attrs={'class': 'special'}), '<textarea rows="10" cols="40" name="msg" class="special"></textarea>')
+
+ self.assertHTMLEqual(w.render('msg', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}), '<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.assertHTMLEqual(w.render('is_cool', ''), '<input type="checkbox" name="is_cool" />')
+ self.assertHTMLEqual(w.render('is_cool', None), '<input type="checkbox" name="is_cool" />')
+ self.assertHTMLEqual(w.render('is_cool', False), '<input type="checkbox" name="is_cool" />')
+ self.assertHTMLEqual(w.render('is_cool', True), '<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.assertHTMLEqual(w.render('is_cool', 'foo'), '<input checked="checked" type="checkbox" name="is_cool" value="foo" />')
+
+ self.assertHTMLEqual(w.render('is_cool', False, attrs={'class': 'pretty'}), '<input type="checkbox" name="is_cool" class="pretty" />')
+
+ # regression for #17114
+ self.assertHTMLEqual(w.render('is_cool', 0), '<input checked="checked" type="checkbox" name="is_cool" value="0" />')
+ self.assertHTMLEqual(w.render('is_cool', 1), '<input checked="checked" type="checkbox" name="is_cool" value="1" />')
+
+ # You can also pass 'attrs' to the constructor:
+ w = CheckboxInput(attrs={'class': 'pretty'})
+ self.assertHTMLEqual(w.render('is_cool', ''), '<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.assertHTMLEqual(w.render('is_cool', '', attrs={'class': 'special'}), '<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.assertHTMLEqual(w.render('greeting', ''), '<input type="checkbox" name="greeting" />')
+ self.assertHTMLEqual(w.render('greeting', 'hello'), '<input checked="checked" type="checkbox" name="greeting" value="hello" />')
+ self.assertHTMLEqual(w.render('greeting', 'hello there'), '<input checked="checked" type="checkbox" name="greeting" value="hello there" />')
+ self.assertHTMLEqual(w.render('greeting', 'hello & goodbye'), '<input checked="checked" type="checkbox" name="greeting" value="hello &amp; goodbye" />')
+
+ # Ticket #17888: calling check_test shouldn't swallow exceptions
+ with self.assertRaises(AttributeError):
+ w.render('greeting', True)
+
+ # 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'))
+
+ value = w.value_from_datadict({'testing': '0'}, {}, 'testing')
+ self.assertIsInstance(value, bool)
+ self.assertTrue(value)
+
+ def test_select(self):
+ w = Select()
+ self.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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>""")
+
+ # Only one option can be selected, see #8103:
+ self.assertHTMLEqual(w.render('choices', '0', choices=(('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('0', 'extra'))), """<select name="choices">
+<option value="0" selected="selected">0</option>
+<option value="1">1</option>
+<option value="2">2</option>
+<option value="3">3</option>
+<option value="0">extra</option>
+</select>""")
+
+ # The value is compared to its str():
+ self.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(f.as_table(), '<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.assertHTMLEqual(f.as_table(), '<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.assertHTMLEqual(f.as_table(), '<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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you &gt; me')))), """<select name="escape">
+<option value="1">1</option>
+<option value="2">2</option>
+<option value="3">3</option>
+<option value="bad">you &amp; me</option>
+<option value="good">you &gt; me</option>
+</select>""")
+
+ # Unicode choices are correctly rendered as HTML
+ self.assertHTMLEqual(w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), '<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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(w.render('nestchoice', None), """<select name="nestchoice">
+<option value="outer1">Outer 1</option>
+<optgroup label="Group &quot;1&quot;">
+<option value="inner1">Inner 1</option>
+<option value="inner2">Inner 2</option>
+</optgroup>
+</select>""")
+
+ self.assertHTMLEqual(w.render('nestchoice', 'outer1'), """<select name="nestchoice">
+<option value="outer1" selected="selected">Outer 1</option>
+<optgroup label="Group &quot;1&quot;">
+<option value="inner1">Inner 1</option>
+<option value="inner2">Inner 2</option>
+</optgroup>
+</select>""")
+
+ self.assertHTMLEqual(w.render('nestchoice', 'inner1'), """<select name="nestchoice">
+<option value="outer1">Outer 1</option>
+<optgroup label="Group &quot;1&quot;">
+<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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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>""")
+
+ def test_selectmultiple(self):
+ w = SelectMultiple()
+ self.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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>""")
+
+ # Multiple options (with the same value) can be selected, see #8103:
+ self.assertHTMLEqual(w.render('choices', ['0'], choices=(('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('0', 'extra'))), """<select multiple="multiple" name="choices">
+<option value="0" selected="selected">0</option>
+<option value="1">1</option>
+<option value="2">2</option>
+<option value="3">3</option>
+<option value="0" selected="selected">extra</option>
+</select>""")
+
+ # If multiple values are given, but some of them are not valid, the valid ones are selected:
+ self.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you &gt; 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 &amp; me</option>
+<option value="good">you &gt; me</option>
+</select>""")
+
+ # Unicode choices are correctly rendered as HTML
+ self.assertHTMLEqual(w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), '<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>')
+
+ # 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.assertHTMLEqual(w.render('nestchoice', None), """<select multiple="multiple" name="nestchoice">
+<option value="outer1">Outer 1</option>
+<optgroup label="Group &quot;1&quot;">
+<option value="inner1">Inner 1</option>
+<option value="inner2">Inner 2</option>
+</optgroup>
+</select>""")
+
+ self.assertHTMLEqual(w.render('nestchoice', ['outer1']), """<select multiple="multiple" name="nestchoice">
+<option value="outer1" selected="selected">Outer 1</option>
+<optgroup label="Group &quot;1&quot;">
+<option value="inner1">Inner 1</option>
+<option value="inner2">Inner 2</option>
+</optgroup>
+</select>""")
+
+ self.assertHTMLEqual(w.render('nestchoice', ['inner1']), """<select multiple="multiple" name="nestchoice">
+<option value="outer1">Outer 1</option>
+<optgroup label="Group &quot;1&quot;">
+<option value="inner1" selected="selected">Inner 1</option>
+<option value="inner2">Inner 2</option>
+</optgroup>
+</select>""")
+
+ self.assertHTMLEqual(w.render('nestchoice', ['outer1', 'inner2']), """<select multiple="multiple" name="nestchoice">
+<option value="outer1" selected="selected">Outer 1</option>
+<optgroup label="Group &quot;1&quot;">
+<option value="inner1">Inner 1</option>
+<option value="inner2" selected="selected">Inner 2</option>
+</optgroup>
+</select>""")
+
+ def test_radioselect(self):
+ w = RadioSelect()
+ self.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual('\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.assertHTMLEqual('\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.assertHTMLEqual('\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.assertHTMLEqual('\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 '<br />\n'.join([six.text_type(choice) for choice in self])
+ w = RadioSelect(renderer=MyRenderer)
+ self.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(str(r[1]), '<label><input type="radio" name="beatle" value="P" /> Paul</label>')
+ self.assertHTMLEqual(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', 'J', 'P', 'Paul'))
+
+ try:
+ r[10]
+ self.fail("This offset should not exist.")
+ except IndexError:
+ pass
+
+ # Choices are escaped correctly
+ w = RadioSelect()
+ self.assertHTMLEqual(w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you &gt; me')))), """<ul>
+<li><label><input type="radio" name="escape" value="bad" /> you &amp; me</label></li>
+<li><label><input type="radio" name="escape" value="good" /> you &gt; me</label></li>
+</ul>""")
+
+ # Unicode choices are correctly rendered as HTML
+ w = RadioSelect()
+ self.assertHTMLEqual(six.text_type(w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')])), '<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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(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.assertHTMLEqual(w.render('escape', None, choices=(('bad', 'you & me'), ('good', mark_safe('you &gt; 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 &amp; me</label></li>
+<li><label><input type="checkbox" name="escape" value="good" /> you &gt; me</label></li>
+</ul>""")
+
+ # Unicode choices are correctly rendered as HTML
+ self.assertHTMLEqual(w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]), '<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.assertHTMLEqual(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>""")
+
+ # Each input gets a separate ID when the ID is passed to the constructor
+ self.assertHTMLEqual(CheckboxSelectMultiple(attrs={'id': 'abc'}).render('letters', list('ac'), choices=zip(list('abc'), list('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 '<br />'.join(rendered_widgets)
+
+ w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'})))
+ self.assertHTMLEqual(w.render('name', ['john', 'lennon']), '<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />')
+ self.assertHTMLEqual(w.render('name', 'john__lennon'), '<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />')
+ self.assertHTMLEqual(w.render('name', 'john__lennon', attrs={'id':'foo'}), '<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.assertHTMLEqual(w.render('name', ['john', 'lennon']), '<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" />')
+
+ def test_splitdatetime(self):
+ w = SplitDateTimeWidget()
+ self.assertHTMLEqual(w.render('date', ''), '<input type="text" name="date_0" /><input type="text" name="date_1" />')
+ self.assertHTMLEqual(w.render('date', None), '<input type="text" name="date_0" /><input type="text" name="date_1" />')
+ self.assertHTMLEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), '<input type="text" name="date_0" value="2006-01-10" /><input type="text" name="date_1" value="07:30:00" />')
+ self.assertHTMLEqual(w.render('date', [datetime.date(2006, 1, 10), datetime.time(7, 30)]), '<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.assertHTMLEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), '<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.assertHTMLEqual(w.render('date', datetime.datetime(2006, 1, 10, 7, 30)), '<input type="text" name="date_0" value="10/01/2006" /><input type="text" name="date_1" value="07:30" />')
+
+ def test_datetimeinput(self):
+ w = DateTimeInput()
+ self.assertHTMLEqual(w.render('date', None), '<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.assertHTMLEqual(w.render('date', d), '<input type="text" name="date" value="2007-09-17 12:51:34" />')
+ self.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51, 34)), '<input type="text" name="date" value="2007-09-17 12:51:34" />')
+ self.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), '<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', attrs={'type': 'datetime'})
+ self.assertHTMLEqual(w.render('date', d), '<input type="datetime" name="date" value="17/09/2007 12:51" />')
+
+ def test_dateinput(self):
+ w = DateInput()
+ self.assertHTMLEqual(w.render('date', None), '<input type="text" name="date" />')
+ d = datetime.date(2007, 9, 17)
+ self.assertEqual(str(d), '2007-09-17')
+
+ self.assertHTMLEqual(w.render('date', d), '<input type="text" name="date" value="2007-09-17" />')
+ self.assertHTMLEqual(w.render('date', datetime.date(2007, 9, 17)), '<input type="text" name="date" value="2007-09-17" />')
+
+ # We should be able to initialize from a unicode value.
+ self.assertHTMLEqual(w.render('date', '2007-09-17'), '<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', attrs={'type': 'date'})
+ self.assertHTMLEqual(w.render('date', d), '<input type="date" name="date" value="17/09/2007" />')
+
+ def test_timeinput(self):
+ w = TimeInput()
+ self.assertHTMLEqual(w.render('time', None), '<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.assertHTMLEqual(w.render('time', t), '<input type="text" name="time" value="12:51:34" />')
+ self.assertHTMLEqual(w.render('time', datetime.time(12, 51, 34)), '<input type="text" name="time" value="12:51:34" />')
+ self.assertHTMLEqual(w.render('time', datetime.time(12, 51)), '<input type="text" name="time" value="12:51:00" />')
+
+ # We should be able to initialize from a unicode value.
+ self.assertHTMLEqual(w.render('time', '13:12:11'), '<input type="text" name="time" value="13:12:11" />')
+
+ # Use 'format' to change the way a value is displayed.
+ w = TimeInput(format='%H:%M', attrs={'type': 'time'})
+ self.assertHTMLEqual(w.render('time', t), '<input type="time" name="time" value="12:51" />')
+
+ def test_splithiddendatetime(self):
+ from django.forms.widgets import SplitHiddenDateTimeWidget
+
+ w = SplitHiddenDateTimeWidget()
+ self.assertHTMLEqual(w.render('date', ''), '<input type="hidden" name="date_0" /><input type="hidden" name="date_1" />')
+ d = datetime.datetime(2007, 9, 17, 12, 51, 34, 482548)
+ self.assertHTMLEqual(str(d), '2007-09-17 12:51:34.482548')
+ self.assertHTMLEqual(w.render('date', d), '<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:34" />')
+ self.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51, 34)), '<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:34" />')
+ self.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), '<input type="hidden" name="date_0" value="2007-09-17" /><input type="hidden" name="date_1" value="12:51:00" />')
+
+
+class NullBooleanSelectLazyForm(Form):
+ """Form to test for lazy evaluation. Refs #17190"""
+ bool = BooleanField(widget=NullBooleanSelect())
+
+@override_settings(USE_L10N=True)
+class FormsI18NWidgetsTestCase(TestCase):
+ def setUp(self):
+ super(FormsI18NWidgetsTestCase, self).setUp()
+ activate('de-at')
+
+ def tearDown(self):
+ deactivate()
+ super(FormsI18NWidgetsTestCase, self).tearDown()
+
+ def test_datetimeinput(self):
+ w = DateTimeInput()
+ d = datetime.datetime(2007, 9, 17, 12, 51, 34, 482548)
+ w.is_localized = True
+ self.assertHTMLEqual(w.render('date', d), '<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.assertHTMLEqual(w.render('date', d), '<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.assertHTMLEqual(w.render('time', t), '<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.assertHTMLEqual(w.render('date', datetime.datetime(2007, 9, 17, 12, 51)), '<input type="hidden" name="date_0" value="17.09.2007" /><input type="hidden" name="date_1" value="12:51:00" />')
+
+ def test_nullbooleanselect(self):
+ """
+ Ensure that the NullBooleanSelect widget's options are lazily
+ localized.
+ Refs #17190
+ """
+ f = NullBooleanSelectLazyForm()
+ self.assertHTMLEqual(f.fields['bool'].widget.render('id_bool', True), '<select name="id_bool">\n<option value="1">Unbekannt</option>\n<option value="2" selected="selected">Ja</option>\n<option value="3">Nein</option>\n</select>')
+
+
+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 LiveWidgetTests(AdminSeleniumWebDriverTestCase):
+ urls = 'forms_tests.urls'
+
+ def test_textarea_trailing_newlines(self):
+ """
+ Test that a roundtrip on a ModelForm doesn't alter the TextField value
+ """
+ article = Article.objects.create(content="\nTst\n")
+ self.selenium.get('%s%s' % (self.live_server_url,
+ reverse('article_form', args=[article.pk])))
+ self.selenium.find_element_by_id('submit').submit()
+ article = Article.objects.get(pk=article.pk)
+ # Should be "\nTst\n" after #19251 is fixed
+ self.assertEqual(article.content, "\r\nTst\r\n")
+
+
+@python_2_unicode_compatible
+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 __str__(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.assertHTMLEqual(widget.render('myfile', FakeFieldFile()),
+ 'Currently: <a 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_html_escaped(self):
+ """
+ A ClearableFileInput should escape name, filename and URL when
+ rendering HTML. Refs #15182.
+ """
+
+ @python_2_unicode_compatible
+ class StrangeFieldFile(object):
+ url = "something?chapter=1&sect=2&copy=3&lang=en"
+
+ def __str__(self):
+ return '''something<div onclick="alert('oops')">.jpg'''
+
+ widget = ClearableFileInput()
+ field = StrangeFieldFile()
+ output = widget.render('my<div>file', field)
+ self.assertFalse(field.url in output)
+ self.assertTrue('href="something?chapter=1&amp;sect=2&amp;copy=3&amp;lang=en"' in output)
+ self.assertFalse(six.text_type(field) in output)
+ self.assertTrue('something&lt;div onclick=&quot;alert(&#39;oops&#39;)&quot;&gt;.jpg' in output)
+ self.assertTrue('my&lt;div&gt;file' in output)
+ self.assertFalse('my<div>file' in output)
+
+ 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.assertHTMLEqual(widget.render('myfile', FakeFieldFile()),
+ 'Currently: <a 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.assertHTMLEqual(widget.render('myfile', None),
+ '<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', b'content')
+ self.assertEqual(widget.value_from_datadict(
+ data={'myfile-clear': True},
+ files={'myfile': f},
+ name='myfile'), f)
diff --git a/tests/forms_tests/urls.py b/tests/forms_tests/urls.py
new file mode 100644
index 0000000000..cbd760081a
--- /dev/null
+++ b/tests/forms_tests/urls.py
@@ -0,0 +1,9 @@
+from django.conf.urls import patterns, url
+from django.views.generic.edit import UpdateView
+
+from .views import ArticleFormView
+
+
+urlpatterns = patterns('',
+ url(r'^model_form/(?P<pk>\d+)/$', ArticleFormView.as_view(), name="article_form"),
+)
diff --git a/tests/forms_tests/views.py b/tests/forms_tests/views.py
new file mode 100644
index 0000000000..4bf384363c
--- /dev/null
+++ b/tests/forms_tests/views.py
@@ -0,0 +1,8 @@
+from django.views.generic.edit import UpdateView
+
+from .models import Article
+
+
+class ArticleFormView(UpdateView):
+ model = Article
+ success_url = '/'