' % e for e in self]))
-...
-
-This form should print errors the default way.
-
->>> form1 = TestForm({'first_name': 'John'})
->>> print form1['last_name'].errors
-
This field is required.
->>> print form1.errors['__all__']
-
I like to be awkward.
-
-This one should wrap error groups in the customized way.
-
->>> form2 = TestForm({'first_name': 'John'}, error_class=CustomErrorList)
->>> print form2['last_name'].errors
-
This field is required.
->>> print form2.errors['__all__']
-
I like to be awkward.
-
-"""
diff --git a/tests/regressiontests/forms/extra.py b/tests/regressiontests/forms/extra.py
deleted file mode 100644
index 57e8e91a60..0000000000
--- a/tests/regressiontests/forms/extra.py
+++ /dev/null
@@ -1,674 +0,0 @@
-# -*- coding: utf-8 -*-
-tests = r"""
->>> from django.forms import *
->>> from django.utils.encoding import force_unicode
->>> import datetime
->>> import time
->>> import re
->>> from decimal import Decimal
-
-###############
-# Extra stuff #
-###############
-
-The forms library comes with some extra, higher-level Field and Widget
-classes that demonstrate some of the library's abilities.
-
-# SelectDateWidget ############################################################
-
->>> from django.forms.extras import SelectDateWidget
->>> w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016'))
->>> print w.render('mydate', '')
-
-
-
->>> w.render('mydate', None) == w.render('mydate', '')
-True
->>> print w.render('mydate', '2010-04-15')
-
-
-
-
-Accepts a datetime or a string:
-
->>> w.render('mydate', datetime.date(2010, 4, 15)) == w.render('mydate', '2010-04-15')
-True
-
-Invalid dates still render the failed date:
->>> print w.render('mydate', '2010-02-31')
-
-
-
-
-Using a SelectDateWidget in a form:
-
->>> w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016'), required=False)
->>> print w.render('mydate', '')
-
-
-
->>> print w.render('mydate', '2010-04-15')
-
-
-
->>> class GetDate(Form):
-... mydate = DateField(widget=SelectDateWidget)
->>> a = GetDate({'mydate_month':'4', 'mydate_day':'1', 'mydate_year':'2008'})
->>> print a.is_valid()
-True
->>> print a.cleaned_data['mydate']
-2008-04-01
-
-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.
-
->>> print a['mydate'].as_hidden()
-
->>> b=GetDate({'mydate':'2008-4-1'})
->>> print b.is_valid()
-True
->>> print b.cleaned_data['mydate']
-2008-04-01
-
-
-USE_L10N tests
-
->>> from django.utils import translation
->>> translation.activate('nl')
->>> from django.conf import settings
->>> settings.USE_L10N=True
-
->>> w.value_from_datadict({'date_year': '2010', 'date_month': '8', 'date_day': '13'}, {}, 'date')
-'13-08-2010'
-
->>> print w.render('date', '13-08-2010')
-
-
-
-
-Years before 1900 work
->>> w = SelectDateWidget(years=('1899',))
->>> w.value_from_datadict({'date_year': '1899', 'date_month': '8', 'date_day': '13'}, {}, 'date')
-'13-08-1899'
-
->>> translation.deactivate()
-
-# MultiWidget and MultiValueField #############################################
-# MultiWidgets are widgets composed of other widgets. They are usually
-# combined with MultiValueFields - a field that is composed of other fields.
-# MulitWidgets can themselved be composed of other MultiWidgets.
-# SplitDateTimeWidget is one example of a MultiWidget.
-
->>> class ComplexMultiWidget(MultiWidget):
-... def __init__(self, attrs=None):
-... widgets = (
-... TextInput(),
-... SelectMultiple(choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))),
-... SplitDateTimeWidget(),
-... )
-... super(ComplexMultiWidget, self).__init__(widgets, attrs)
-...
-... def decompress(self, value):
-... if value:
-... data = value.split(',')
-... return [data[0], data[1], datetime.datetime(*time.strptime(data[2], "%Y-%m-%d %H:%M:%S")[0:6])]
-... return [None, None, None]
-... def format_output(self, rendered_widgets):
-... return u'\n'.join(rendered_widgets)
->>> w = ComplexMultiWidget()
->>> print w.render('name', 'some text,JP,2007-04-25 06:24:00')
-
-
-
-
->>> class ComplexField(MultiValueField):
-... def __init__(self, required=True, widget=None, label=None, initial=None):
-... fields = (
-... CharField(),
-... MultipleChoiceField(choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))),
-... SplitDateTimeField()
-... )
-... super(ComplexField, self).__init__(fields, required, widget, label, initial)
-...
-... def compress(self, data_list):
-... if data_list:
-... return '%s,%s,%s' % (data_list[0],''.join(data_list[1]),data_list[2])
-... return None
-
->>> f = ComplexField(widget=w)
->>> f.clean(['some text', ['J','P'], ['2007-04-25','6:24:00']])
-u'some text,JP,2007-04-25 06:24:00'
->>> f.clean(['some text',['X'], ['2007-04-25','6:24:00']])
-Traceback (most recent call last):
-...
-ValidationError: [u'Select a valid choice. X is not one of the available choices.']
-
-# If insufficient data is provided, None is substituted
->>> f.clean(['some text',['JP']])
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
-
->>> class ComplexFieldForm(Form):
-... field1 = ComplexField(widget=w)
->>> f = ComplexFieldForm()
->>> print f
-
-
-
-
->>> f = ComplexFieldForm({'field1_0':'some text','field1_1':['J','P'], 'field1_2_0':'2007-04-25', 'field1_2_1':'06:24:00'})
->>> print f
-
-
-
-
->>> f.cleaned_data['field1']
-u'some text,JP,2007-04-25 06:24:00'
-
-
-# IPAddressField ##################################################################
-
->>> f = IPAddressField()
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean('127.0.0.1')
-u'127.0.0.1'
->>> f.clean('foo')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid IPv4 address.']
->>> f.clean('127.0.0.')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid IPv4 address.']
->>> f.clean('1.2.3.4.5')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid IPv4 address.']
->>> f.clean('256.125.1.5')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid IPv4 address.']
-
->>> f = IPAddressField(required=False)
->>> f.clean('')
-u''
->>> f.clean(None)
-u''
->>> f.clean('127.0.0.1')
-u'127.0.0.1'
->>> f.clean('foo')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid IPv4 address.']
->>> f.clean('127.0.0.')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid IPv4 address.']
->>> f.clean('1.2.3.4.5')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid IPv4 address.']
->>> f.clean('256.125.1.5')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid IPv4 address.']
-
-#################################
-# Tests of underlying functions #
-#################################
-
-# smart_unicode tests
->>> from django.utils.encoding import smart_unicode
->>> class Test:
-... def __str__(self):
-... return 'ŠĐĆŽćžšđ'
->>> class TestU:
-... def __str__(self):
-... return 'Foo'
-... def __unicode__(self):
-... return u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111'
->>> smart_unicode(Test())
-u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111'
->>> smart_unicode(TestU())
-u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111'
->>> smart_unicode(1)
-u'1'
->>> smart_unicode('foo')
-u'foo'
-
-
-####################################
-# Test accessing errors in clean() #
-####################################
-
->>> class UserForm(Form):
-... username = CharField(max_length=10)
-... password = CharField(widget=PasswordInput)
-... def clean(self):
-... data = self.cleaned_data
-... if not self.errors:
-... data['username'] = data['username'].lower()
-... return data
-
->>> f = UserForm({'username': 'SirRobin', 'password': 'blue'})
->>> f.is_valid()
-True
->>> f.cleaned_data['username']
-u'sirrobin'
-
-#######################################
-# Test overriding ErrorList in a form #
-#######################################
-
->>> from django.forms.util import ErrorList
->>> class DivErrorList(ErrorList):
-... def __unicode__(self):
-... return self.as_divs()
-... def as_divs(self):
-... if not self: return u''
-... return u'
%s
' % ''.join([u'
%s
' % force_unicode(e) for e in self])
->>> class CommentForm(Form):
-... name = CharField(max_length=50, required=False)
-... email = EmailField()
-... comment = CharField()
->>> data = dict(email='invalid')
->>> f = CommentForm(data, auto_id=False, error_class=DivErrorList)
->>> print f.as_p()
-
Name:
-
Enter a valid e-mail address.
-
Email:
-
This field is required.
-
Comment:
-
-#################################
-# Test multipart-encoded form #
-#################################
-
->>> class FormWithoutFile(Form):
-... username = CharField()
->>> class FormWithFile(Form):
-... username = CharField()
-... file = FileField()
->>> class FormWithImage(Form):
-... image = ImageField()
-
->>> FormWithoutFile().is_multipart()
-False
->>> FormWithFile().is_multipart()
-True
->>> FormWithImage().is_multipart()
-True
-
-"""
diff --git a/tests/regressiontests/forms/fields.py b/tests/regressiontests/forms/fields.py
deleted file mode 100644
index b3212eada2..0000000000
--- a/tests/regressiontests/forms/fields.py
+++ /dev/null
@@ -1,864 +0,0 @@
-# -*- 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.
-"""
-import datetime
-import time
-import re
-import os
-from decimal import Decimal
-
-from django.core.files.uploadedfile import SimpleUploadedFile
-from django.forms import *
-from django.forms.widgets import RadioFieldRenderer
-from django.utils.unittest import TestCase
-
-
-def fix_os_paths(x):
- if isinstance(x, basestring):
- 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(TestCase):
-
- def assertRaisesErrorWithMessage(self, error, message, callable, *args, **kwargs):
- self.assertRaises(error, callable, *args, **kwargs)
- try:
- callable(*args, **kwargs)
- except error, e:
- self.assertEqual(message, str(e))
-
- def test_field_sets_widget_is_required(self):
- self.assertEqual(Field(required=True).widget.is_required, True)
- self.assertEqual(Field(required=False).widget.is_required, False)
-
- # CharField ###################################################################
-
- def test_charfield_0(self):
- f = CharField()
- self.assertEqual(u'1', f.clean(1))
- self.assertEqual(u'hello', f.clean('hello'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
- self.assertEqual(u'[1, 2, 3]', f.clean([1, 2, 3]))
-
- def test_charfield_1(self):
- f = CharField(required=False)
- self.assertEqual(u'1', f.clean(1))
- self.assertEqual(u'hello', f.clean('hello'))
- self.assertEqual(u'', f.clean(None))
- self.assertEqual(u'', f.clean(''))
- self.assertEqual(u'[1, 2, 3]', f.clean([1, 2, 3]))
-
- def test_charfield_2(self):
- f = CharField(max_length=10, required=False)
- self.assertEqual(u'12345', f.clean('12345'))
- self.assertEqual(u'1234567890', f.clean('1234567890'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 10 characters (it has 11).']", f.clean, '1234567890a')
-
- def test_charfield_3(self):
- f = CharField(min_length=10, required=False)
- self.assertEqual(u'', f.clean(''))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 5).']", f.clean, '12345')
- self.assertEqual(u'1234567890', f.clean('1234567890'))
- self.assertEqual(u'1234567890a', f.clean('1234567890a'))
-
- def test_charfield_4(self):
- f = CharField(min_length=10, required=True)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 5).']", f.clean, '12345')
- self.assertEqual(u'1234567890', f.clean('1234567890'))
- self.assertEqual(u'1234567890a', f.clean('1234567890a'))
-
- # IntegerField ################################################################
-
- def test_integerfield_5(self):
- f = IntegerField()
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'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.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, 'a')
- self.assertEqual(42, f.clean(42))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'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.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, '1a')
-
- def test_integerfield_6(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.assertRaisesErrorWithMessage(ValidationError, "[u'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.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, '1a')
-
- def test_integerfield_7(self):
- f = IntegerField(max_value=10)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None)
- self.assertEqual(1, f.clean(1))
- self.assertEqual(10, f.clean(10))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 10.']", f.clean, 11)
- self.assertEqual(10, f.clean('10'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 10.']", f.clean, '11')
-
- def test_integerfield_8(self):
- f = IntegerField(min_value=10)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 10.']", f.clean, 1)
- self.assertEqual(10, f.clean(10))
- self.assertEqual(11, f.clean(11))
- self.assertEqual(10, f.clean('10'))
- self.assertEqual(11, f.clean('11'))
-
- def test_integerfield_9(self):
- f = IntegerField(min_value=10, max_value=20)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 10.']", f.clean, 1)
- 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.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 20.']", f.clean, 21)
-
- # FloatField ##################################################################
-
- def test_floatfield_10(self):
- f = FloatField()
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'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.assertRaisesErrorWithMessage(ValidationError, "[u'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.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, '1.0a')
-
- def test_floatfield_11(self):
- f = FloatField(required=False)
- self.assertEqual(None, f.clean(''))
- self.assertEqual(None, f.clean(None))
- self.assertEqual(1.0, f.clean('1'))
-
- def test_floatfield_12(self):
- f = FloatField(max_value=1.5, min_value=0.5)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 1.5.']", f.clean, '1.6')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 0.5.']", f.clean, '0.4')
- self.assertEqual(1.5, f.clean('1.5'))
- self.assertEqual(0.5, f.clean('0.5'))
-
- # DecimalField ################################################################
-
- def test_decimalfield_13(self):
- f = DecimalField(max_digits=4, decimal_places=2)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None)
- 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.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, 'NaN')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, 'Inf')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, '-Inf')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, 'a')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, u'łąść')
- 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.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, '1.0a')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '123.45')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '1.234')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'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.assertRaisesErrorWithMessage(ValidationError, "[u'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.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '-000.123')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '-000.12345')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, '--0.12')
-
- def test_decimalfield_14(self):
- f = DecimalField(max_digits=4, decimal_places=2, required=False)
- self.assertEqual(None, f.clean(''))
- self.assertEqual(None, f.clean(None))
- self.assertEqual(f.clean('1'), Decimal("1"))
-
- def test_decimalfield_15(self):
- f = DecimalField(max_digits=4, decimal_places=2, max_value=Decimal('1.5'), min_value=Decimal('0.5'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 1.5.']", f.clean, '1.6')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 0.5.']", f.clean, '0.4')
- 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"))
-
- def test_decimalfield_16(self):
- f = DecimalField(decimal_places=2)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '0.00000001')
-
- def test_decimalfield_17(self):
- 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.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 3 digits in total.']", f.clean, '000000.0002')
- self.assertEqual(f.clean('.002'), Decimal("0.002"))
-
- def test_decimalfield_18(self):
- f = DecimalField(max_digits=2, decimal_places=2)
- self.assertEqual(f.clean('.01'), Decimal(".01"))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 0 digits before the decimal point.']", f.clean, '1.1')
-
- # DateField ###################################################################
-
- def test_datefield_19(self):
- 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.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '2006-4-31')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '200a-10-25')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '25/10/06')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None)
-
- def test_datefield_20(self):
- f = DateField(required=False)
- self.assertEqual(None, f.clean(None))
- self.assertEqual('None', repr(f.clean(None)))
- self.assertEqual(None, f.clean(''))
- self.assertEqual('None', repr(f.clean('')))
-
- def test_datefield_21(self):
- 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.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '2006-10-25')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '10/25/2006')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '10/25/06')
-
- # TimeField ###################################################################
-
- def test_timefield_22(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.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, 'hello')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, '1:24 p.m.')
-
- def test_timefield_23(self):
- 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.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, '14:30:45')
-
- # DateTimeField ###############################################################
-
- def test_datetimefield_24(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), 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), 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), 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.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, 'hello')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, '2006-10-25 4:30 p.m.')
-
- def test_datetimefield_25(self):
- 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.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, '2006-10-25 14:30:45')
-
- def test_datetimefield_26(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('')))
-
- # RegexField ##################################################################
-
- def test_regexfield_27(self):
- f = RegexField('^\d[A-F]\d$')
- self.assertEqual(u'2A2', f.clean('2A2'))
- self.assertEqual(u'3F3', f.clean('3F3'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, ' 2A2')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '2A2 ')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
-
- def test_regexfield_28(self):
- f = RegexField('^\d[A-F]\d$', required=False)
- self.assertEqual(u'2A2', f.clean('2A2'))
- self.assertEqual(u'3F3', f.clean('3F3'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3')
- self.assertEqual(u'', f.clean(''))
-
- def test_regexfield_29(self):
- f = RegexField(re.compile('^\d[A-F]\d$'))
- self.assertEqual(u'2A2', f.clean('2A2'))
- self.assertEqual(u'3F3', f.clean('3F3'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, ' 2A2')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '2A2 ')
-
- def test_regexfield_30(self):
- f = RegexField('^\d\d\d\d$', error_message='Enter a four-digit number.')
- self.assertEqual(u'1234', f.clean('1234'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a four-digit number.']", f.clean, '123')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a four-digit number.']", f.clean, 'abcd')
-
- def test_regexfield_31(self):
- f = RegexField('^\d+$', min_length=5, max_length=10)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 5 characters (it has 3).']", f.clean, '123')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 5 characters (it has 3).', u'Enter a valid value.']", f.clean, 'abc')
- self.assertEqual(u'12345', f.clean('12345'))
- self.assertEqual(u'1234567890', f.clean('1234567890'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 10 characters (it has 11).']", f.clean, '12345678901')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '12345a')
-
- # EmailField ##################################################################
-
- def test_emailfield_32(self):
- f = EmailField()
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None)
- self.assertEqual(u'person@example.com', f.clean('person@example.com'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@bar')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@invalid-.com')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@-invalid.com')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@inv-.alid-.com')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@inv-.-alid.com')
- self.assertEqual(u'example@valid-----hyphens.com', f.clean('example@valid-----hyphens.com'))
- self.assertEqual(u'example@valid-with-hyphens.com', f.clean('example@valid-with-hyphens.com'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@.com')
- self.assertEqual(u'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.
- self.assertRaisesErrorWithMessage(
- ValidationError,
- "[u'Enter a valid e-mail address.']",
- f.clean,
- 'viewx3dtextx26qx3d@yahoo.comx26latlngx3d15854521645943074058'
- )
-
- def test_emailfield_33(self):
- f = EmailField(required=False)
- self.assertEqual(u'', f.clean(''))
- self.assertEqual(u'', f.clean(None))
- self.assertEqual(u'person@example.com', f.clean('person@example.com'))
- self.assertEqual(u'example@example.com', f.clean(' example@example.com \t \t '))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@bar')
-
- def test_emailfield_34(self):
- f = EmailField(min_length=10, max_length=15)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 9).']", f.clean, 'a@foo.com')
- self.assertEqual(u'alf@foo.com', f.clean('alf@foo.com'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 15 characters (it has 20).']", f.clean, 'alf123456788@foo.com')
-
- # FileField ##################################################################
-
- def test_filefield_35(self):
- f = FileField()
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '', '')
- self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None, '')
- self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, SimpleUploadedFile('', ''))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, SimpleUploadedFile('', ''), '')
- self.assertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, 'some content that is not a file')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'The submitted file is empty.']", f.clean, SimpleUploadedFile('name', None))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'The submitted file is empty.']", f.clean, SimpleUploadedFile('name', ''))
- self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content'))))
- self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'))))
- self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content'), 'files/test4.pdf')))
-
- def test_filefield_36(self):
- f = FileField(max_length = 5)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this filename has at most 5 characters (it has 18).']", f.clean, SimpleUploadedFile('test_maxlength.txt', 'hello world'))
- self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf'))
- self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
- self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content'))))
-
- # URLField ##################################################################
-
- def test_urlfield_37(self):
- f = URLField()
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None)
- self.assertEqual(u'http://localhost/', f.clean('http://localhost'))
- self.assertEqual(u'http://example.com/', f.clean('http://example.com'))
- self.assertEqual(u'http://example.com./', f.clean('http://example.com.'))
- self.assertEqual(u'http://www.example.com/', f.clean('http://www.example.com'))
- self.assertEqual(u'http://www.example.com:8000/test', f.clean('http://www.example.com:8000/test'))
- self.assertEqual(u'http://valid-with-hyphens.com/', f.clean('valid-with-hyphens.com'))
- self.assertEqual(u'http://subdomain.domain.com/', f.clean('subdomain.domain.com'))
- self.assertEqual(u'http://200.8.9.10/', f.clean('http://200.8.9.10'))
- self.assertEqual(u'http://200.8.9.10:8000/test', f.clean('http://200.8.9.10:8000/test'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'foo')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example.')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'com.')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, '.')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://.com')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://invalid-.com')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://-invalid.com')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://inv-.alid-.com')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://inv-.-alid.com')
- self.assertEqual(u'http://valid-----hyphens.com/', f.clean('http://valid-----hyphens.com'))
- self.assertEqual(u'http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah'))
-
- def test_url_regex_ticket11198(self):
- f = URLField()
- # hangs "forever" if catastrophic backtracking in ticket:#11198 not fixed
- self.assertRaisesErrorWithMessage(ValidationError, "[u'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.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://%s' % ("X"*60,))
-
- def test_urlfield_38(self):
- f = URLField(required=False)
- self.assertEqual(u'', f.clean(''))
- self.assertEqual(u'', f.clean(None))
- self.assertEqual(u'http://example.com/', f.clean('http://example.com'))
- self.assertEqual(u'http://www.example.com/', f.clean('http://www.example.com'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'foo')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example.')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://.com')
-
- def test_urlfield_39(self):
- f = URLField(verify_exists=True)
- self.assertEqual(u'http://www.google.com/', f.clean('http://www.google.com')) # This will fail if there's no Internet connection
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example')
- self.assertRaises(ValidationError, f.clean, 'http://www.broken.djangoproject.com') # bad domain
- try:
- f.clean('http://www.broken.djangoproject.com') # bad domain
- except ValidationError, e:
- self.assertEqual("[u'This URL appears to be a broken link.']", str(e))
- self.assertRaises(ValidationError, f.clean, 'http://google.com/we-love-microsoft.html') # good domain, bad page
- try:
- f.clean('http://google.com/we-love-microsoft.html') # good domain, bad page
- except ValidationError, e:
- self.assertEqual("[u'This URL appears to be a broken link.']", str(e))
- # Valid and existent IDN
- self.assertEqual(u'http://\u05e2\u05d1\u05e8\u05d9\u05ea.idn.icann.org/', f.clean(u'http://עברית.idn.icann.org/'))
- # Valid but non-existent IDN
- try:
- f.clean(u'http://broken.עברית.idn.icann.org/')
- except ValidationError, e:
- self.assertEqual("[u'This URL appears to be a broken link.']", str(e))
-
- def test_urlfield_40(self):
- f = URLField(verify_exists=True, required=False)
- self.assertEqual(u'', f.clean(''))
- self.assertEqual(u'http://www.google.com/', f.clean('http://www.google.com')) # This will fail if there's no Internet connection
-
- def test_urlfield_41(self):
- f = URLField(min_length=15, max_length=20)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 15 characters (it has 13).']", f.clean, 'http://f.com')
- self.assertEqual(u'http://example.com/', f.clean('http://example.com'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 38).']", f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com')
-
- def test_urlfield_42(self):
- f = URLField(required=False)
- self.assertEqual(u'http://example.com/', f.clean('example.com'))
- self.assertEqual(u'', f.clean(''))
- self.assertEqual(u'https://example.com/', f.clean('https://example.com'))
-
- def test_urlfield_43(self):
- f = URLField()
- self.assertEqual(u'http://example.com/', f.clean('http://example.com'))
- self.assertEqual(u'http://example.com/test', f.clean('http://example.com/test'))
-
- def test_urlfield_ticket11826(self):
- f = URLField()
- self.assertEqual(u'http://example.com/?some_param=some_value', f.clean('http://example.com?some_param=some_value'))
-
- # BooleanField ################################################################
-
- def test_booleanfield_44(self):
- f = BooleanField()
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None)
- self.assertEqual(True, f.clean(True))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, False)
- self.assertEqual(True, f.clean(1))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, 0)
- self.assertEqual(True, f.clean('Django rocks'))
- self.assertEqual(True, f.clean('True'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, 'False')
-
- def test_booleanfield_45(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'))
-
- # ChoiceField #################################################################
-
- def test_choicefield_46(self):
- f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')])
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None)
- self.assertEqual(u'1', f.clean(1))
- self.assertEqual(u'1', f.clean('1'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, '3')
-
- def test_choicefield_47(self):
- f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
- self.assertEqual(u'', f.clean(''))
- self.assertEqual(u'', f.clean(None))
- self.assertEqual(u'1', f.clean(1))
- self.assertEqual(u'1', f.clean('1'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, '3')
-
- def test_choicefield_48(self):
- f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')])
- self.assertEqual(u'J', f.clean('J'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. John is not one of the available choices.']", f.clean, 'John')
-
- def test_choicefield_49(self):
- f = ChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')])
- self.assertEqual(u'1', f.clean(1))
- self.assertEqual(u'1', f.clean('1'))
- self.assertEqual(u'3', f.clean(3))
- self.assertEqual(u'3', f.clean('3'))
- self.assertEqual(u'5', f.clean(5))
- self.assertEqual(u'5', f.clean('5'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'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_50(self):
- f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
- self.assertEqual(1, f.clean('1'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 2 is not one of the available choices.']", f.clean, '2')
-
- def test_typedchoicefield_51(self):
- # Different coercion, same validation.
- f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=float)
- self.assertEqual(1.0, f.clean('1'))
-
- def test_typedchoicefield_52(self):
- # This can also cause weirdness: be careful (bool(-1) == True, remember)
- f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=bool)
- self.assertEqual(True, f.clean('-1'))
-
- def test_typedchoicefield_53(self):
- # Even more weirdness: if you have a valid choice but your coercion function
- # can't coerce, you'll still get a validation error. Don't do this!
- f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. B is not one of the available choices.']", f.clean, 'B')
- # Required fields require values
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
-
- def test_typedchoicefield_54(self):
- # Non-required fields aren't required
- f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False)
- self.assertEqual('', f.clean(''))
- # If you want cleaning an empty value to return a different type, tell the field
-
- def test_typedchoicefield_55(self):
- f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None)
- self.assertEqual(None, f.clean(''))
-
- # NullBooleanField ############################################################
-
- def test_nullbooleanfield_56(self):
- 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_57(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.assertEqual('', str(f))
-
- def test_nullbooleanfield_58(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_59(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'])
-
- # MultipleChoiceField #########################################################
-
- def test_multiplechoicefield_60(self):
- f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')])
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None)
- self.assertEqual([u'1'], f.clean([1]))
- self.assertEqual([u'1'], f.clean(['1']))
- self.assertEqual([u'1', u'2'], f.clean(['1', '2']))
- self.assertEqual([u'1', u'2'], f.clean([1, '2']))
- self.assertEqual([u'1', u'2'], f.clean((1, '2')))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, [])
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, ())
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, ['3'])
-
- def test_multiplechoicefield_61(self):
- f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
- self.assertEqual([], f.clean(''))
- self.assertEqual([], f.clean(None))
- self.assertEqual([u'1'], f.clean([1]))
- self.assertEqual([u'1'], f.clean(['1']))
- self.assertEqual([u'1', u'2'], f.clean(['1', '2']))
- self.assertEqual([u'1', u'2'], f.clean([1, '2']))
- self.assertEqual([u'1', u'2'], f.clean((1, '2')))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello')
- self.assertEqual([], f.clean([]))
- self.assertEqual([], f.clean(()))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, ['3'])
-
- def test_multiplechoicefield_62(self):
- f = MultipleChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')])
- self.assertEqual([u'1'], f.clean([1]))
- self.assertEqual([u'1'], f.clean(['1']))
- self.assertEqual([u'1', u'5'], f.clean([1, 5]))
- self.assertEqual([u'1', u'5'], f.clean([1, '5']))
- self.assertEqual([u'1', u'5'], f.clean(['1', 5]))
- self.assertEqual([u'1', u'5'], f.clean(['1', '5']))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, ['6'])
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, ['1','6'])
-
- # ComboField ##################################################################
-
- def test_combofield_63(self):
- f = ComboField(fields=[CharField(max_length=20), EmailField()])
- self.assertEqual(u'test@example.com', f.clean('test@example.com'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 28).']", f.clean, 'longemailaddress@example.com')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'not an e-mail')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None)
-
- def test_combofield_64(self):
- f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False)
- self.assertEqual(u'test@example.com', f.clean('test@example.com'))
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 28).']", f.clean, 'longemailaddress@example.com')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'not an e-mail')
- self.assertEqual(u'', f.clean(''))
- self.assertEqual(u'', f.clean(None))
-
- # FilePathField ###############################################################
-
- def test_filepathfield_65(self):
- path = os.path.abspath(forms.__file__)
- path = os.path.dirname(path) + '/'
- self.assertTrue(fix_os_paths(path).endswith('/django/forms/'))
-
- def test_filepathfield_66(self):
- path = 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.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. fields.py is not one of the available choices.']", f.clean, 'fields.py')
- assert fix_os_paths(f.clean(path + 'fields.py')).endswith('/django/forms/fields.py')
-
- def test_filepathfield_67(self):
- path = 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_68(self):
- path = os.path.abspath(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]))
-
- # SplitDateTimeField ##########################################################
-
- def test_splitdatetimefield_69(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.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None)
- self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.', u'Enter a valid time.']", f.clean, ['hello', 'there'])
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', 'there'])
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['hello', '07:30'])
-
- def test_splitdatetimefield_70(self):
- 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.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello')
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.', u'Enter a valid time.']", f.clean, ['hello', 'there'])
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', 'there'])
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['hello', '07:30'])
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', ''])
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10'])
- self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['', '07:30'])
diff --git a/tests/regressiontests/forms/forms.py b/tests/regressiontests/forms/forms.py
deleted file mode 100644
index 91594139f2..0000000000
--- a/tests/regressiontests/forms/forms.py
+++ /dev/null
@@ -1,1899 +0,0 @@
-# -*- coding: utf-8 -*-
-tests = r"""
->>> from django.forms import *
->>> from django.core.files.uploadedfile import SimpleUploadedFile
->>> import datetime
->>> import time
->>> import re
->>> from decimal import Decimal
-
-#########
-# Forms #
-#########
-
-A Form is a collection of Fields. It knows how to validate a set of data and it
-knows how to render itself in a couple of default ways (e.g., an HTML table).
-You can pass it data in __init__(), as a dictionary.
-
-# Form ########################################################################
-
->>> class Person(Form):
-... first_name = CharField()
-... last_name = CharField()
-... birthday = DateField()
-
-Pass a dictionary to a Form's __init__().
->>> p = Person({'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9'})
->>> p.is_bound
-True
->>> p.errors
-{}
->>> p.is_valid()
-True
->>> p.errors.as_ul()
-u''
->>> p.errors.as_text()
-u''
->>> p.cleaned_data["first_name"], p.cleaned_data["last_name"], p.cleaned_data["birthday"]
-(u'John', u'Lennon', datetime.date(1940, 10, 9))
->>> print p['first_name']
-
->>> print p['last_name']
-
->>> print p['birthday']
-
->>> print p['nonexistentfield']
-Traceback (most recent call last):
-...
-KeyError: "Key 'nonexistentfield' not found in Form"
-
->>> for boundfield in p:
-... print boundfield
-
-
-
->>> for boundfield in p:
-... print boundfield.label, boundfield.data
-First name John
-Last name Lennon
-Birthday 1940-10-9
->>> print p
-
-
-
-
-Empty dictionaries are valid, too.
->>> p = Person({})
->>> p.is_bound
-True
->>> p.errors['first_name']
-[u'This field is required.']
->>> p.errors['last_name']
-[u'This field is required.']
->>> p.errors['birthday']
-[u'This field is required.']
->>> p.is_valid()
-False
->>> p.cleaned_data
-Traceback (most recent call last):
-...
-AttributeError: 'Person' object has no attribute 'cleaned_data'
->>> print p
-
This field is required.
-
This field is required.
-
This field is required.
->>> print p.as_table()
-
This field is required.
-
This field is required.
-
This field is required.
->>> print p.as_ul()
-
This field is required.
-
This field is required.
-
This field is required.
->>> print p.as_p()
-
This field is required.
-
-
This field is required.
-
-
This field is required.
-
-
-If you don't pass any values to the Form's __init__(), or if you pass None,
-the Form will be considered unbound and won't do any validation. Form.errors
-will be an empty dictionary *but* Form.is_valid() will return False.
->>> p = Person()
->>> p.is_bound
-False
->>> p.errors
-{}
->>> p.is_valid()
-False
->>> p.cleaned_data
-Traceback (most recent call last):
-...
-AttributeError: 'Person' object has no attribute 'cleaned_data'
->>> print p
-
-
-
->>> print p.as_table()
-
-
-
->>> print p.as_ul()
-
-
-
->>> print p.as_p()
-
-
-
-
-Unicode values are handled properly.
->>> p = Person({'first_name': u'John', 'last_name': u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'})
->>> p.as_table()
-u'
\n
\n
'
->>> p.as_ul()
-u'
\n
\n
'
->>> p.as_p()
-u'
\n
\n
'
-
->>> p = Person({'last_name': u'Lennon'})
->>> p.errors['first_name']
-[u'This field is required.']
->>> p.errors['birthday']
-[u'This field is required.']
->>> p.is_valid()
-False
->>> p.errors.as_ul()
-u'
first_name
This field is required.
birthday
This field is required.
'
->>> print p.errors.as_text()
-* first_name
- * This field is required.
-* birthday
- * This field is required.
->>> p.cleaned_data
-Traceback (most recent call last):
-...
-AttributeError: 'Person' object has no attribute 'cleaned_data'
->>> p['first_name'].errors
-[u'This field is required.']
->>> p['first_name'].errors.as_ul()
-u'
This field is required.
'
->>> p['first_name'].errors.as_text()
-u'* This field is required.'
-
->>> p = Person()
->>> print p['first_name']
-
->>> print p['last_name']
-
->>> print p['birthday']
-
-
-cleaned_data will always *only* contain a key for fields defined in the
-Form, even if you pass extra data when you define the Form. In this
-example, we pass a bunch of extra fields to the form constructor,
-but cleaned_data contains only the form's fields.
->>> data = {'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9', 'extra1': 'hello', 'extra2': 'hello'}
->>> p = Person(data)
->>> p.is_valid()
-True
->>> p.cleaned_data['first_name']
-u'John'
->>> p.cleaned_data['last_name']
-u'Lennon'
->>> p.cleaned_data['birthday']
-datetime.date(1940, 10, 9)
-
-
-cleaned_data will include a key and value for *all* fields defined in the Form,
-even if the Form's data didn't include a value for fields that are not
-required. In this example, the data dictionary doesn't include a value for the
-"nick_name" field, but cleaned_data includes it. For CharFields, it's set to the
-empty string.
->>> class OptionalPersonForm(Form):
-... first_name = CharField()
-... last_name = CharField()
-... nick_name = CharField(required=False)
->>> data = {'first_name': u'John', 'last_name': u'Lennon'}
->>> f = OptionalPersonForm(data)
->>> f.is_valid()
-True
->>> f.cleaned_data['nick_name']
-u''
->>> f.cleaned_data['first_name']
-u'John'
->>> f.cleaned_data['last_name']
-u'Lennon'
-
-For DateFields, it's set to None.
->>> class OptionalPersonForm(Form):
-... first_name = CharField()
-... last_name = CharField()
-... birth_date = DateField(required=False)
->>> data = {'first_name': u'John', 'last_name': u'Lennon'}
->>> f = OptionalPersonForm(data)
->>> f.is_valid()
-True
->>> print f.cleaned_data['birth_date']
-None
->>> f.cleaned_data['first_name']
-u'John'
->>> f.cleaned_data['last_name']
-u'Lennon'
-
-"auto_id" tells the Form to add an "id" attribute to each form element.
-If it's a string that contains '%s', Django will use that as a format string
-into which the field's name will be inserted. It will also put a
-
-MultipleChoiceField is a special case, as its data is required to be a list:
->>> class SongForm(Form):
-... name = CharField()
-... composers = MultipleChoiceField()
->>> f = SongForm(auto_id=False)
->>> print f['composers']
-
->>> class SongForm(Form):
-... name = CharField()
-... composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')])
->>> f = SongForm(auto_id=False)
->>> print f['composers']
-
->>> f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
->>> print f['name']
-
->>> print f['composers']
-
-
-MultipleChoiceField rendered as_hidden() is a special case. Because it can
-have multiple values, its as_hidden() renders multiple
-tags.
->>> f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
->>> print f['composers'].as_hidden()
-
->>> f = SongForm({'name': 'From Me To You', 'composers': ['P', 'J']}, auto_id=False)
->>> print f['composers'].as_hidden()
-
-
-
-DateTimeField rendered as_hidden() is special too
-
->>> class MessageForm(Form):
-... when = SplitDateTimeField()
->>> f = MessageForm({'when_0': '1992-01-01', 'when_1': '01:01'})
->>> print f.is_valid()
-True
->>> print f['when']
-
->>> print f['when'].as_hidden()
-
-
-MultipleChoiceField can also be used with the CheckboxSelectMultiple widget.
->>> class SongForm(Form):
-... name = CharField()
-... composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
->>> f = SongForm(auto_id=False)
->>> print f['composers']
-
-
John Lennon
-
Paul McCartney
-
->>> f = SongForm({'composers': ['J']}, auto_id=False)
->>> print f['composers']
-
-
-Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox
-gets a distinct ID, formed by appending an underscore plus the checkbox's
-zero-based index.
->>> f = SongForm(auto_id='%s_id')
->>> print f['composers']
-
-
John Lennon
-
Paul McCartney
-
-
-Data for a MultipleChoiceField should be a list. QueryDict, MultiValueDict and
-MergeDict (when created as a merge of MultiValueDicts) conveniently work with
-this.
->>> data = {'name': 'Yesterday', 'composers': ['J', 'P']}
->>> f = SongForm(data)
->>> f.errors
-{}
->>> from django.http import QueryDict
->>> data = QueryDict('name=Yesterday&composers=J&composers=P')
->>> f = SongForm(data)
->>> f.errors
-{}
->>> from django.utils.datastructures import MultiValueDict
->>> data = MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P']))
->>> f = SongForm(data)
->>> f.errors
-{}
->>> from django.utils.datastructures import MergeDict
->>> data = MergeDict(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])))
->>> f = SongForm(data)
->>> f.errors
-{}
-
-The MultipleHiddenInput widget renders multiple values as hidden fields.
->>> class SongFormHidden(Form):
-... name = CharField()
-... composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=MultipleHiddenInput)
->>> f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False)
->>> print f.as_ul()
-
Name:
-
-
-When using CheckboxSelectMultiple, the framework expects a list of input and
-returns a list of input.
->>> f = SongForm({'name': 'Yesterday'}, auto_id=False)
->>> f.errors['composers']
-[u'This field is required.']
->>> f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False)
->>> f.errors
-{}
->>> f.cleaned_data['composers']
-[u'J']
->>> f.cleaned_data['name']
-u'Yesterday'
->>> f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False)
->>> f.errors
-{}
->>> f.cleaned_data['composers']
-[u'J', u'P']
->>> f.cleaned_data['name']
-u'Yesterday'
-
-Validation errors are HTML-escaped when output as HTML.
->>> from django.utils.safestring import mark_safe
->>> class EscapingForm(Form):
-... special_name = CharField(label="Special Field")
-... special_safe_name = CharField(label=mark_safe("Special 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("'%s' is a safe string" % self.cleaned_data['special_safe_name']))
-
->>> f = EscapingForm({'special_name': "Nothing to escape", 'special_safe_name': "Nothing to escape"}, auto_id=False)
->>> print f
-
<em>Special</em> Field:
Something's wrong with 'Nothing to escape'
-
Special Field:
'Nothing to escape' is a safe string
->>> f = EscapingForm(
-... {'special_name': "Should escape < & > and ",
-... 'special_safe_name': "Do not escape"}, auto_id=False)
->>> print f
-
<em>Special</em> Field:
Something's wrong with 'Should escape < & > and <script>alert('xss')</script>'
-
Special Field:
'Do not escape' is a safe string
-
-""" + \
-r""" # [This concatenation is to keep the string below the jython's 32K limit].
-# Validating multiple fields in relation to another ###########################
-
-There are a couple of ways to do multiple-field validation. If you want the
-validation message to be associated with a particular field, implement the
-clean_XXX() method on the Form, where XXX is the field name. As in
-Field.clean(), the clean_XXX() method should return the cleaned value. In the
-clean_XXX() method, you have access to self.cleaned_data, which is a dictionary
-of all the data that has been cleaned *so far*, in order by the fields,
-including the current field (e.g., the field XXX if you're in clean_XXX()).
->>> class UserRegistration(Form):
-... username = CharField(max_length=10)
-... password1 = CharField(widget=PasswordInput)
-... password2 = CharField(widget=PasswordInput)
-... def clean_password2(self):
-... if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
-... raise ValidationError(u'Please make sure your passwords match.')
-... return self.cleaned_data['password2']
->>> f = UserRegistration(auto_id=False)
->>> f.errors
-{}
->>> f = UserRegistration({}, auto_id=False)
->>> f.errors['username']
-[u'This field is required.']
->>> f.errors['password1']
-[u'This field is required.']
->>> f.errors['password2']
-[u'This field is required.']
->>> f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
->>> f.errors['password2']
-[u'Please make sure your passwords match.']
->>> f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
->>> f.errors
-{}
->>> f.cleaned_data['username']
-u'adrian'
->>> f.cleaned_data['password1']
-u'foo'
->>> f.cleaned_data['password2']
-u'foo'
-
-Another way of doing multiple-field validation is by implementing the
-Form's clean() method. If you do this, any ValidationError raised by that
-method will not be associated with a particular field; it will have a
-special-case association with the field named '__all__'.
-Note that in Form.clean(), you have access to self.cleaned_data, a dictionary of
-all the fields/values that have *not* raised a ValidationError. Also note
-Form.clean() is required to return a dictionary of all clean data.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10)
-... password1 = CharField(widget=PasswordInput)
-... password2 = CharField(widget=PasswordInput)
-... def clean(self):
-... if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
-... raise ValidationError(u'Please make sure your passwords match.')
-... return self.cleaned_data
->>> f = UserRegistration(auto_id=False)
->>> f.errors
-{}
->>> f = UserRegistration({}, auto_id=False)
->>> print f.as_table()
-
Username:
This field is required.
-
Password1:
This field is required.
-
Password2:
This field is required.
->>> f.errors['username']
-[u'This field is required.']
->>> f.errors['password1']
-[u'This field is required.']
->>> f.errors['password2']
-[u'This field is required.']
->>> f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
->>> f.errors['__all__']
-[u'Please make sure your passwords match.']
->>> print f.as_table()
-
Please make sure your passwords match.
-
Username:
-
Password1:
-
Password2:
->>> print f.as_ul()
-
Please make sure your passwords match.
-
Username:
-
Password1:
-
Password2:
->>> f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
->>> f.errors
-{}
->>> f.cleaned_data['username']
-u'adrian'
->>> f.cleaned_data['password1']
-u'foo'
->>> f.cleaned_data['password2']
-u'foo'
-
-# Dynamic construction ########################################################
-
-It's possible to construct a Form dynamically by adding to the self.fields
-dictionary in __init__(). Don't forget to call Form.__init__() within the
-subclass' __init__().
->>> class Person(Form):
-... first_name = CharField()
-... last_name = CharField()
-... def __init__(self, *args, **kwargs):
-... super(Person, self).__init__(*args, **kwargs)
-... self.fields['birthday'] = DateField()
->>> p = Person(auto_id=False)
->>> print p
-
First name:
-
Last name:
-
Birthday:
-
-Instances of a dynamic Form do not persist fields from one Form instance to
-the next.
->>> class MyForm(Form):
-... def __init__(self, data=None, auto_id=False, field_list=[]):
-... Form.__init__(self, data, auto_id=auto_id)
-... for field in field_list:
-... self.fields[field[0]] = field[1]
->>> field_list = [('field1', CharField()), ('field2', CharField())]
->>> my_form = MyForm(field_list=field_list)
->>> print my_form
-
-
-Similarly, changes to field attributes do not persist from one Form instance
-to the next.
->>> class Person(Form):
-... first_name = CharField(required=False)
-... last_name = CharField(required=False)
-... def __init__(self, names_required=False, *args, **kwargs):
-... super(Person, self).__init__(*args, **kwargs)
-... if names_required:
-... self.fields['first_name'].required = True
-... self.fields['first_name'].widget.attrs['class'] = 'required'
-... self.fields['last_name'].required = True
-... self.fields['last_name'].widget.attrs['class'] = 'required'
->>> f = Person(names_required=False)
->>> f['first_name'].field.required, f['last_name'].field.required
-(False, False)
->>> f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs
-({}, {})
->>> f = Person(names_required=True)
->>> f['first_name'].field.required, f['last_name'].field.required
-(True, True)
->>> f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs
-({'class': 'required'}, {'class': 'required'})
->>> f = Person(names_required=False)
->>> f['first_name'].field.required, f['last_name'].field.required
-(False, False)
->>> f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs
-({}, {})
->>> class Person(Form):
-... first_name = CharField(max_length=30)
-... last_name = CharField(max_length=30)
-... def __init__(self, name_max_length=None, *args, **kwargs):
-... super(Person, self).__init__(*args, **kwargs)
-... if name_max_length:
-... self.fields['first_name'].max_length = name_max_length
-... self.fields['last_name'].max_length = name_max_length
->>> f = Person(name_max_length=None)
->>> f['first_name'].field.max_length, f['last_name'].field.max_length
-(30, 30)
->>> f = Person(name_max_length=20)
->>> f['first_name'].field.max_length, f['last_name'].field.max_length
-(20, 20)
->>> f = Person(name_max_length=None)
->>> f['first_name'].field.max_length, f['last_name'].field.max_length
-(30, 30)
-
-HiddenInput widgets are displayed differently in the as_table(), as_ul()
-and as_p() output of a Form -- their verbose names are not displayed, and a
-separate row is not displayed. They're displayed in the last row of the
-form, directly after that row's form element.
->>> class Person(Form):
-... first_name = CharField()
-... last_name = CharField()
-... hidden_text = CharField(widget=HiddenInput)
-... birthday = DateField()
->>> p = Person(auto_id=False)
->>> print p
-
First name:
-
Last name:
-
Birthday:
->>> print p.as_ul()
-
First name:
-
Last name:
-
Birthday:
->>> print p.as_p()
-
First name:
-
Last name:
-
Birthday:
-
-With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
->>> p = Person(auto_id='id_%s')
->>> print p
-
First name:
-
Last name:
-
Birthday:
->>> print p.as_ul()
-
First name:
-
Last name:
-
Birthday:
->>> print p.as_p()
-
First name:
-
Last name:
-
Birthday:
-
-If a field with a HiddenInput has errors, the as_table() and as_ul() output
-will include the error message(s) with the text "(Hidden field [fieldname]) "
-prepended. This message is displayed at the top of the output, regardless of
-its field's order in the form.
->>> p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False)
->>> print p
-
(Hidden field hidden_text) This field is required.
-
First name:
-
Last name:
-
Birthday:
->>> print p.as_ul()
-
(Hidden field hidden_text) This field is required.
-
First name:
-
Last name:
-
Birthday:
->>> print p.as_p()
-
(Hidden field hidden_text) This field is required.
-
First name:
-
Last name:
-
Birthday:
-
-A corner case: It's possible for a form to have only HiddenInputs.
->>> class TestForm(Form):
-... foo = CharField(widget=HiddenInput)
-... bar = CharField(widget=HiddenInput)
->>> p = TestForm(auto_id=False)
->>> print p.as_table()
-
->>> print p.as_ul()
-
->>> print p.as_p()
-
-
-A Form's fields are displayed in the same order in which they were defined.
->>> class TestForm(Form):
-... field1 = CharField()
-... field2 = CharField()
-... field3 = CharField()
-... field4 = CharField()
-... field5 = CharField()
-... field6 = CharField()
-... field7 = CharField()
-... field8 = CharField()
-... field9 = CharField()
-... field10 = CharField()
-... field11 = CharField()
-... field12 = CharField()
-... field13 = CharField()
-... field14 = CharField()
->>> p = TestForm(auto_id=False)
->>> print p
-
Field1:
-
Field2:
-
Field3:
-
Field4:
-
Field5:
-
Field6:
-
Field7:
-
Field8:
-
Field9:
-
Field10:
-
Field11:
-
Field12:
-
Field13:
-
Field14:
-
-Some Field classes have an effect on the HTML attributes of their associated
-Widget. If you set max_length in a CharField and its associated widget is
-either a TextInput or PasswordInput, then the widget's rendered HTML will
-include the "maxlength" attribute.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10) # uses TextInput by default
-... password = CharField(max_length=10, widget=PasswordInput)
-... realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test
-... address = CharField() # no max_length defined here
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-
Username:
-
Password:
-
Realname:
-
Address:
-
-If you specify a custom "attrs" that includes the "maxlength" attribute,
-the Field's max_length attribute will override whatever "maxlength" you specify
-in "attrs".
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, widget=TextInput(attrs={'maxlength': 20}))
-... password = CharField(max_length=10, widget=PasswordInput)
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-
Username:
-
Password:
-
-# Specifying labels ###########################################################
-
-You can specify the label for a field by using the 'label' argument to a Field
-class. If you don't specify 'label', Django will use the field name with
-underscores converted to spaces, and the initial letter capitalized.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, label='Your username')
-... password1 = CharField(widget=PasswordInput)
-... password2 = CharField(widget=PasswordInput, label='Password (again)')
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-
Your username:
-
Password1:
-
Password (again):
-
-Labels for as_* methods will only end in a colon if they don't end in other
-punctuation already.
->>> class Questions(Form):
-... q1 = CharField(label='The first question')
-... q2 = CharField(label='What is your name?')
-... q3 = CharField(label='The answer to life is:')
-... q4 = CharField(label='Answer this question!')
-... q5 = CharField(label='The last question. Period.')
->>> print Questions(auto_id=False).as_p()
-
The first question:
-
What is your name?
-
The answer to life is:
-
Answer this question!
-
The last question. Period.
->>> print Questions().as_p()
-
The first question:
-
What is your name?
-
The answer to life is:
-
Answer this question!
-
The last question. Period.
-
-A label can be a Unicode object or a bytestring with special characters.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, label='ŠĐĆŽćžšđ')
-... password = CharField(widget=PasswordInput, label=u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111')
->>> p = UserRegistration(auto_id=False)
->>> p.as_ul()
-u'
\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111:
\n
\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111:
'
-
-If a label is set to the empty string for a field, that field won't get a label.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, label='')
-... password = CharField(widget=PasswordInput)
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-
-
Password:
->>> p = UserRegistration(auto_id='id_%s')
->>> print p.as_ul()
-
-
Password:
-
-If label is None, Django will auto-create the label from the field name. This
-is default behavior.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, label=None)
-... password = CharField(widget=PasswordInput)
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-
Username:
-
Password:
->>> p = UserRegistration(auto_id='id_%s')
->>> print p.as_ul()
-
Username:
-
Password:
-
-
-# Label Suffix ################################################################
-
-You can specify the 'label_suffix' argument to a Form class to modify the
-punctuation symbol used at the end of a label. By default, the colon (:) is
-used, and is only appended to the label if the label doesn't already end with a
-punctuation symbol: ., !, ? or :. If you specify a different suffix, it will
-be appended regardless of the last character of the label.
-
->>> class FavoriteForm(Form):
-... color = CharField(label='Favorite color?')
-... animal = CharField(label='Favorite animal')
-...
->>> f = FavoriteForm(auto_id=False)
->>> print f.as_ul()
-
Favorite color?
-
Favorite animal:
->>> f = FavoriteForm(auto_id=False, label_suffix='?')
->>> print f.as_ul()
-
Favorite color?
-
Favorite animal?
->>> f = FavoriteForm(auto_id=False, label_suffix='')
->>> print f.as_ul()
-
Favorite color?
-
Favorite animal
->>> f = FavoriteForm(auto_id=False, label_suffix=u'\u2192')
->>> f.as_ul()
-u'
Favorite color?
\n
Favorite animal\u2192
'
-
-""" + \
-r""" # [This concatenation is to keep the string below the jython's 32K limit].
-
-# Initial data ################################################################
-
-You can specify initial data for a field by using the 'initial' argument to a
-Field class. This initial data is displayed when a Form is rendered with *no*
-data. It is not displayed when a Form is rendered with any data (including an
-empty dictionary). Also, the initial value is *not* used if data for a
-particular required field isn't provided.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, initial='django')
-... password = CharField(widget=PasswordInput)
-
-Here, we're not submitting any data, so the initial value will be displayed.
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-
Username:
-
Password:
-
-Here, we're submitting data, so the initial value will *not* be displayed.
->>> p = UserRegistration({}, auto_id=False)
->>> print p.as_ul()
-
This field is required.
Username:
-
This field is required.
Password:
->>> p = UserRegistration({'username': u''}, auto_id=False)
->>> print p.as_ul()
-
This field is required.
Username:
-
This field is required.
Password:
->>> p = UserRegistration({'username': u'foo'}, auto_id=False)
->>> print p.as_ul()
-
Username:
-
This field is required.
Password:
-
-An 'initial' value is *not* used as a fallback if data is not provided. In this
-example, we don't provide a value for 'username', and the form raises a
-validation error rather than using the initial value for 'username'.
->>> p = UserRegistration({'password': 'secret'})
->>> p.errors['username']
-[u'This field is required.']
->>> p.is_valid()
-False
-
-# Dynamic initial data ########################################################
-
-The previous technique dealt with "hard-coded" initial data, but it's also
-possible to specify initial data after you've already created the Form class
-(i.e., at runtime). Use the 'initial' parameter to the Form constructor. This
-should be a dictionary containing initial values for one or more fields in the
-form, keyed by field name.
-
->>> class UserRegistration(Form):
-... username = CharField(max_length=10)
-... password = CharField(widget=PasswordInput)
-
-Here, we're not submitting any data, so the initial value will be displayed.
->>> p = UserRegistration(initial={'username': 'django'}, auto_id=False)
->>> print p.as_ul()
-
Username:
-
Password:
->>> p = UserRegistration(initial={'username': 'stephane'}, auto_id=False)
->>> print p.as_ul()
-
Username:
-
Password:
-
-The 'initial' parameter is meaningless if you pass data.
->>> p = UserRegistration({}, initial={'username': 'django'}, auto_id=False)
->>> print p.as_ul()
-
-
-A dynamic 'initial' value is *not* used as a fallback if data is not provided.
-In this example, we don't provide a value for 'username', and the form raises a
-validation error rather than using the initial value for 'username'.
->>> p = UserRegistration({'password': 'secret'}, initial={'username': 'django'})
->>> p.errors['username']
-[u'This field is required.']
->>> p.is_valid()
-False
-
-If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
-then the latter will get precedence.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, initial='django')
-... password = CharField(widget=PasswordInput)
->>> p = UserRegistration(initial={'username': 'babik'}, auto_id=False)
->>> print p.as_ul()
-
Username:
-
Password:
-
-# Callable initial data ########################################################
-
-The previous technique dealt with raw values as initial data, but it's also
-possible to specify callable data.
-
->>> class UserRegistration(Form):
-... username = CharField(max_length=10)
-... password = CharField(widget=PasswordInput)
-... options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')])
-
-We need to define functions that get called later.
->>> def initial_django():
-... return 'django'
->>> def initial_stephane():
-... return 'stephane'
->>> def initial_options():
-... return ['f','b']
->>> def initial_other_options():
-... return ['b','w']
-
-
-Here, we're not submitting any data, so the initial value will be displayed.
->>> p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False)
->>> print p.as_ul()
-
Username:
-
Password:
-
Options:
-
-The 'initial' parameter is meaningless if you pass data.
->>> p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False)
->>> print p.as_ul()
-
-
-A callable 'initial' value is *not* used as a fallback if data is not provided.
-In this example, we don't provide a value for 'username', and the form raises a
-validation error rather than using the initial value for 'username'.
->>> p = UserRegistration({'password': 'secret'}, initial={'username': initial_django, 'options': initial_options})
->>> p.errors['username']
-[u'This field is required.']
->>> p.is_valid()
-False
-
-If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
-then the latter will get precedence.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, initial=initial_django)
-... password = CharField(widget=PasswordInput)
-... options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')], initial=initial_other_options)
-
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-
-
-# Help text ###################################################################
-
-You can specify descriptive text for a field by using the 'help_text' argument
-to a Field class. This help text is displayed when a Form is rendered.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, help_text='e.g., user@example.com')
-... password = CharField(widget=PasswordInput, help_text='Choose wisely.')
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-
Username: e.g., user@example.com
-
Password: Choose wisely.
->>> print p.as_p()
-
Username: e.g., user@example.com
-
Password: Choose wisely.
->>> print p.as_table()
-
Username:
e.g., user@example.com
-
Password:
Choose wisely.
-
-The help text is displayed whether or not data is provided for the form.
->>> p = UserRegistration({'username': u'foo'}, auto_id=False)
->>> print p.as_ul()
-
Username: e.g., user@example.com
-
This field is required.
Password: Choose wisely.
-
-help_text is not displayed for hidden fields. It can be used for documentation
-purposes, though.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, help_text='e.g., user@example.com')
-... password = CharField(widget=PasswordInput)
-... next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination')
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-
Username: e.g., user@example.com
-
Password:
-
-Help text can include arbitrary Unicode characters.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, help_text='ŠĐĆŽćžšđ')
->>> p = UserRegistration(auto_id=False)
->>> p.as_ul()
-u'
'
-
-# Subclassing forms ###########################################################
-
-You can subclass a Form to add fields. The resulting form subclass will have
-all of the fields of the parent Form, plus whichever fields you define in the
-subclass.
->>> class Person(Form):
-... first_name = CharField()
-... last_name = CharField()
-... birthday = DateField()
->>> class Musician(Person):
-... instrument = CharField()
->>> p = Person(auto_id=False)
->>> print p.as_ul()
-
First name:
-
Last name:
-
Birthday:
->>> m = Musician(auto_id=False)
->>> print m.as_ul()
-
First name:
-
Last name:
-
Birthday:
-
Instrument:
-
-Yes, you can subclass multiple forms. The fields are added in the order in
-which the parent classes are listed.
->>> class Person(Form):
-... first_name = CharField()
-... last_name = CharField()
-... birthday = DateField()
->>> class Instrument(Form):
-... instrument = CharField()
->>> class Beatle(Person, Instrument):
-... haircut_type = CharField()
->>> b = Beatle(auto_id=False)
->>> print b.as_ul()
-
First name:
-
Last name:
-
Birthday:
-
Instrument:
-
Haircut type:
-
-# Forms with prefixes #########################################################
-
-Sometimes it's necessary to have multiple forms display on the same HTML page,
-or multiple copies of the same form. We can accomplish this with form prefixes.
-Pass the keyword argument 'prefix' to the Form constructor to use this feature.
-This value will be prepended to each HTML form field name. One way to think
-about this is "namespaces for HTML forms". Notice that in the data argument,
-each field's key has the prefix, in this case 'person1', prepended to the
-actual field name.
->>> class Person(Form):
-... first_name = CharField()
-... last_name = CharField()
-... birthday = DateField()
->>> data = {
-... 'person1-first_name': u'John',
-... 'person1-last_name': u'Lennon',
-... 'person1-birthday': u'1940-10-9'
-... }
->>> p = Person(data, prefix='person1')
->>> print p.as_ul()
-
First name:
-
Last name:
-
Birthday:
->>> print p['first_name']
-
->>> print p['last_name']
-
->>> print p['birthday']
-
->>> p.errors
-{}
->>> p.is_valid()
-True
->>> p.cleaned_data['first_name']
-u'John'
->>> p.cleaned_data['last_name']
-u'Lennon'
->>> p.cleaned_data['birthday']
-datetime.date(1940, 10, 9)
-
-Let's try submitting some bad data to make sure form.errors and field.errors
-work as expected.
->>> data = {
-... 'person1-first_name': u'',
-... 'person1-last_name': u'',
-... 'person1-birthday': u''
-... }
->>> p = Person(data, prefix='person1')
->>> p.errors['first_name']
-[u'This field is required.']
->>> p.errors['last_name']
-[u'This field is required.']
->>> p.errors['birthday']
-[u'This field is required.']
->>> p['first_name'].errors
-[u'This field is required.']
->>> p['person1-first_name'].errors
-Traceback (most recent call last):
-...
-KeyError: "Key 'person1-first_name' not found in Form"
-
-In this example, the data doesn't have a prefix, but the form requires it, so
-the form doesn't "see" the fields.
->>> data = {
-... 'first_name': u'John',
-... 'last_name': u'Lennon',
-... 'birthday': u'1940-10-9'
-... }
->>> p = Person(data, prefix='person1')
->>> p.errors['first_name']
-[u'This field is required.']
->>> p.errors['last_name']
-[u'This field is required.']
->>> p.errors['birthday']
-[u'This field is required.']
-
-With prefixes, a single data dictionary can hold data for multiple instances
-of the same form.
->>> data = {
-... 'person1-first_name': u'John',
-... 'person1-last_name': u'Lennon',
-... 'person1-birthday': u'1940-10-9',
-... 'person2-first_name': u'Jim',
-... 'person2-last_name': u'Morrison',
-... 'person2-birthday': u'1943-12-8'
-... }
->>> p1 = Person(data, prefix='person1')
->>> p1.is_valid()
-True
->>> p1.cleaned_data['first_name']
-u'John'
->>> p1.cleaned_data['last_name']
-u'Lennon'
->>> p1.cleaned_data['birthday']
-datetime.date(1940, 10, 9)
->>> p2 = Person(data, prefix='person2')
->>> p2.is_valid()
-True
->>> p2.cleaned_data['first_name']
-u'Jim'
->>> p2.cleaned_data['last_name']
-u'Morrison'
->>> p2.cleaned_data['birthday']
-datetime.date(1943, 12, 8)
-
-By default, forms append a hyphen between the prefix and the field name, but a
-form can alter that behavior by implementing the add_prefix() method. This
-method takes a field name and returns the prefixed field, according to
-self.prefix.
->>> class Person(Form):
-... first_name = CharField()
-... last_name = CharField()
-... birthday = DateField()
-... def add_prefix(self, field_name):
-... return self.prefix and '%s-prefix-%s' % (self.prefix, field_name) or field_name
->>> p = Person(prefix='foo')
->>> print p.as_ul()
-
First name:
-
Last name:
-
Birthday:
->>> data = {
-... 'foo-prefix-first_name': u'John',
-... 'foo-prefix-last_name': u'Lennon',
-... 'foo-prefix-birthday': u'1940-10-9'
-... }
->>> p = Person(data, prefix='foo')
->>> p.is_valid()
-True
->>> p.cleaned_data['first_name']
-u'John'
->>> p.cleaned_data['last_name']
-u'Lennon'
->>> p.cleaned_data['birthday']
-datetime.date(1940, 10, 9)
-
-# Forms with NullBooleanFields ################################################
-
-NullBooleanField is a bit of a special case because its presentation (widget)
-is different than its data. This is handled transparently, though.
-
->>> class Person(Form):
-... name = CharField()
-... is_cool = NullBooleanField()
->>> p = Person({'name': u'Joe'}, auto_id=False)
->>> print p['is_cool']
-
->>> p = Person({'name': u'Joe', 'is_cool': u'1'}, auto_id=False)
->>> print p['is_cool']
-
->>> p = Person({'name': u'Joe', 'is_cool': u'2'}, auto_id=False)
->>> print p['is_cool']
-
->>> p = Person({'name': u'Joe', 'is_cool': u'3'}, auto_id=False)
->>> print p['is_cool']
-
->>> p = Person({'name': u'Joe', 'is_cool': True}, auto_id=False)
->>> print p['is_cool']
-
->>> p = Person({'name': u'Joe', 'is_cool': False}, auto_id=False)
->>> print p['is_cool']
-
-
-# Forms with FileFields ################################################
-
-FileFields are a special case because they take their data from the request.FILES,
-not request.POST.
-
->>> class FileForm(Form):
-... file1 = FileField()
->>> f = FileForm(auto_id=False)
->>> print f
-
File1:
-
->>> f = FileForm(data={}, files={}, auto_id=False)
->>> print f
-
File1:
This field is required.
-
->>> f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', '')}, auto_id=False)
->>> print f
-
File1:
The submitted file is empty.
-
->>> f = FileForm(data={}, files={'file1': 'something that is not a file'}, auto_id=False)
->>> print f
-
File1:
No file was submitted. Check the encoding type on the form.
-
->>> f = FileForm(data={}, files={'file1': SimpleUploadedFile('name', 'some content')}, auto_id=False)
->>> print f
-
File1:
->>> f.is_valid()
-True
-
->>> f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')}, auto_id=False)
->>> print f
-
File1:
-
-# Basic form processing in a view #############################################
-
->>> from django.template import Template, Context
->>> class UserRegistration(Form):
-... username = CharField(max_length=10)
-... password1 = CharField(widget=PasswordInput)
-... password2 = CharField(widget=PasswordInput)
-... def clean(self):
-... if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
-... raise ValidationError(u'Please make sure your passwords match.')
-... return self.cleaned_data
->>> def my_function(method, post_data):
-... if method == 'POST':
-... form = UserRegistration(post_data, auto_id=False)
-... else:
-... form = UserRegistration(auto_id=False)
-... if form.is_valid():
-... return 'VALID: %r' % form.cleaned_data
-... t = Template('')
-... return t.render(Context({'form': form}))
-
-Case 1: GET (an empty form, with no errors).
->>> print my_function('GET', {})
-
-
-Case 2: POST with erroneous data (a redisplayed form, with errors).
->>> print my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'})
-
-
-Case 3: POST with valid data (the success message).
->>> print my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'})
-VALID: {'username': u'adrian', 'password1': u'secret', 'password2': u'secret'}
-
-# Some ideas for using templates with forms ###################################
-
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, help_text="Good luck picking a username that doesn't already exist.")
-... password1 = CharField(widget=PasswordInput)
-... password2 = CharField(widget=PasswordInput)
-... def clean(self):
-... if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
-... raise ValidationError(u'Please make sure your passwords match.')
-... return self.cleaned_data
-
-You have full flexibility in displaying form fields in a template. Just pass a
-Form instance to the template, and use "dot" access to refer to individual
-fields. Note, however, that this flexibility comes with the responsibility of
-displaying all the errors, including any that might not be associated with a
-particular field.
->>> t = Template('''''')
->>> print t.render(Context({'form': UserRegistration(auto_id=False)}))
-
->>> print t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)}))
-
-
-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('''''')
->>> print t.render(Context({'form': UserRegistration(auto_id=False)}))
-
-
-User form.[field].label_tag to output a field's label with a 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('''''')
->>> print t.render(Context({'form': UserRegistration(auto_id=False)}))
-
->>> print t.render(Context({'form': UserRegistration(auto_id='id_%s')}))
-
-
-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('''''')
->>> print t.render(Context({'form': UserRegistration(auto_id=False)}))
-
->>> Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)}))
-u''
-
-The label_tag() method takes an optional attrs argument: a dictionary of HTML
-attributes to add to the tag.
->>> f = UserRegistration(auto_id='id_%s')
->>> for bf in f:
-... print bf.label_tag(attrs={'class': 'pretty'})
-Username
-Password1
-Password2
-
-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
(or an empty string, if
-the list of errors is empty). You can also use it in {% if %} statements.
->>> t = Template('''
''')
->>> print t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)}))
-
->>> t = Template('''''')
->>> print t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)}))
-
-
-
-# The empty_permitted attribute ##############################################
-
-Sometimes (pretty much in formsets) we want to allow a form to pass validation
-if it is completely empty. We can accomplish this by using the empty_permitted
-agrument to a form constructor.
-
->>> class SongForm(Form):
-... artist = CharField()
-... name = CharField()
-
-First let's show what happens id empty_permitted=False (the default):
-
->>> data = {'artist': '', 'song': ''}
-
->>> form = SongForm(data, empty_permitted=False)
->>> form.is_valid()
-False
->>> form.errors
-{'name': [u'This field is required.'], 'artist': [u'This field is required.']}
->>> form.cleaned_data
-Traceback (most recent call last):
-...
-AttributeError: 'SongForm' object has no attribute 'cleaned_data'
-
-
-Now let's show what happens when empty_permitted=True and the form is empty.
-
->>> form = SongForm(data, empty_permitted=True)
->>> form.is_valid()
-True
->>> form.errors
-{}
->>> form.cleaned_data
-{}
-
-But if we fill in data for one of the fields, the form is no longer empty and
-the whole thing must pass validation.
-
->>> data = {'artist': 'The Doors', 'song': ''}
->>> form = SongForm(data, empty_permitted=False)
->>> form.is_valid()
-False
->>> form.errors
-{'name': [u'This field is required.']}
->>> form.cleaned_data
-Traceback (most recent call last):
-...
-AttributeError: 'SongForm' object has no attribute 'cleaned_data'
-
-If a field is not given in the data then None is returned for its data. Lets
-make sure that when checking for empty_permitted that None is treated
-accordingly.
-
->>> data = {'artist': None, 'song': ''}
->>> form = SongForm(data, empty_permitted=True)
->>> form.is_valid()
-True
-
-However, we *really* need to be sure we are checking for None as any data in
-initial that returns False on a boolean call needs to be treated literally.
-
->>> class PriceForm(Form):
-... amount = FloatField()
-... qty = IntegerField()
-
->>> data = {'amount': '0.0', 'qty': ''}
->>> form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True)
->>> form.is_valid()
-True
-
-# Extracting hidden and visible fields ######################################
-
->>> class SongForm(Form):
-... token = CharField(widget=HiddenInput)
-... artist = CharField()
-... name = CharField()
->>> form = SongForm()
->>> [f.name for f in form.hidden_fields()]
-['token']
->>> [f.name for f in form.visible_fields()]
-['artist', 'name']
-
-# Hidden initial input gets its own unique id ################################
-
->>> class MyForm(Form):
-... field1 = CharField(max_length=50, show_hidden_initial=True)
->>> print MyForm()
-
Field1:
-
-# The error_html_class and required_html_class attributes ####################
-
->>> class Person(Form):
-... name = CharField()
-... is_cool = NullBooleanField()
-... email = EmailField(required=False)
-... age = IntegerField()
-
->>> p = Person({})
->>> p.error_css_class = 'error'
->>> p.required_css_class = 'required'
-
->>> print p.as_ul()
-
This field is required.
Name:
-
Is cool:
-
Email:
-
This field is required.
Age:
-
->>> print p.as_p()
-
This field is required.
-
Name:
-
Is cool:
-
Email:
-
This field is required.
-
Age:
-
->>> print p.as_table()
-
Name:
This field is required.
-
Is cool:
-
Email:
-
Age:
This field is required.
-
-
-
-# Checking that the label for SplitDateTimeField is not being displayed #####
-
->>> class EventForm(Form):
-... happened_at = SplitDateTimeField(widget=widgets.SplitHiddenDateTimeWidget)
-...
->>> form = EventForm()
->>> form.as_ul()
-u''
-
-"""
diff --git a/tests/regressiontests/forms/formsets.py b/tests/regressiontests/forms/formsets.py
deleted file mode 100644
index f8b8ae2a8a..0000000000
--- a/tests/regressiontests/forms/formsets.py
+++ /dev/null
@@ -1,762 +0,0 @@
-# -*- coding: utf-8 -*-
-from django.test.testcases import TestCase
-from django.forms.forms import Form
-from django.forms.fields import CharField, IntegerField
-from django.forms.formsets import formset_factory
-tests = """
-# Basic FormSet creation and usage ############################################
-
-FormSet allows us to use multiple instance of the same form on 1 page. For now,
-the best way to create a FormSet is by using the formset_factory function.
-
->>> from django.forms import Form, CharField, IntegerField, ValidationError
->>> from django.forms.formsets import formset_factory, BaseFormSet
-
->>> class Choice(Form):
-... choice = CharField()
-... votes = IntegerField()
-
->>> ChoiceFormSet = formset_factory(Choice)
-
-A FormSet constructor takes the same arguments as Form. Let's create a FormSet
-for adding data. By default, it displays 1 blank form. It can display more,
-but we'll look at how to do so later.
-
->>> formset = ChoiceFormSet(auto_id=False, prefix='choices')
->>> print formset
-
-
Choice:
-
Votes:
-
-
-On thing to note is that there needs to be a special value in the data. This
-value tells the FormSet how many forms were displayed so it can tell how
-many forms it needs to clean and validate. You could use javascript to create
-new forms on the client side, but they won't get validated unless you increment
-the TOTAL_FORMS field appropriately.
-
->>> data = {
-... 'choices-TOTAL_FORMS': '1', # the number of forms rendered
-... 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
-... 'choices-MAX_NUM_FORMS': '0', # max number of forms
-... 'choices-0-choice': 'Calexico',
-... 'choices-0-votes': '100',
-... }
-
-We treat FormSet pretty much like we would treat a normal Form. FormSet has an
-is_valid method, and a cleaned_data or errors attribute depending on whether all
-the forms passed validation. However, unlike a Form instance, cleaned_data and
-errors will be a list of dicts rather than just a single dict.
-
->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
->>> formset.is_valid()
-True
->>> [form.cleaned_data for form in formset.forms]
-[{'votes': 100, 'choice': u'Calexico'}]
-
-If a FormSet was not passed any data, its is_valid method should return False.
->>> formset = ChoiceFormSet()
->>> formset.is_valid()
-False
-
-FormSet instances can also have an error attribute if validation failed for
-any of the forms.
-
->>> data = {
-... 'choices-TOTAL_FORMS': '1', # the number of forms rendered
-... 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
-... 'choices-MAX_NUM_FORMS': '0', # max number of forms
-... 'choices-0-choice': 'Calexico',
-... 'choices-0-votes': '',
-... }
-
->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
->>> formset.is_valid()
-False
->>> formset.errors
-[{'votes': [u'This field is required.']}]
-
-
-We can also prefill a FormSet with existing data by providing an ``initial``
-argument to the constructor. ``initial`` should be a list of dicts. By default,
-an extra blank form is included.
-
->>> initial = [{'choice': u'Calexico', 'votes': 100}]
->>> formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
->>> for form in formset.forms:
-... print form.as_ul()
-
Choice:
-
Votes:
-
Choice:
-
Votes:
-
-
-Let's simulate what would happen if we submitted this form.
-
->>> data = {
-... 'choices-TOTAL_FORMS': '2', # the number of forms rendered
-... 'choices-INITIAL_FORMS': '1', # the number of forms with initial data
-... 'choices-MAX_NUM_FORMS': '0', # max number of forms
-... 'choices-0-choice': 'Calexico',
-... 'choices-0-votes': '100',
-... 'choices-1-choice': '',
-... 'choices-1-votes': '',
-... }
-
->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
->>> formset.is_valid()
-True
->>> [form.cleaned_data for form in formset.forms]
-[{'votes': 100, 'choice': u'Calexico'}, {}]
-
-But the second form was blank! Shouldn't we get some errors? No. If we display
-a form as blank, it's ok for it to be submitted as blank. If we fill out even
-one of the fields of a blank form though, it will be validated. We may want to
-required that at least x number of forms are completed, but we'll show how to
-handle that later.
-
->>> data = {
-... 'choices-TOTAL_FORMS': '2', # the number of forms rendered
-... 'choices-INITIAL_FORMS': '1', # the number of forms with initial data
-... 'choices-MAX_NUM_FORMS': '0', # max number of forms
-... 'choices-0-choice': 'Calexico',
-... 'choices-0-votes': '100',
-... 'choices-1-choice': 'The Decemberists',
-... 'choices-1-votes': '', # missing value
-... }
-
->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
->>> formset.is_valid()
-False
->>> formset.errors
-[{}, {'votes': [u'This field is required.']}]
-
-If we delete data that was pre-filled, we should get an error. Simply removing
-data from form fields isn't the proper way to delete it. We'll see how to
-handle that case later.
-
->>> data = {
-... 'choices-TOTAL_FORMS': '2', # the number of forms rendered
-... 'choices-INITIAL_FORMS': '1', # the number of forms with initial data
-... 'choices-MAX_NUM_FORMS': '0', # max number of forms
-... 'choices-0-choice': '', # deleted value
-... 'choices-0-votes': '', # deleted value
-... 'choices-1-choice': '',
-... 'choices-1-votes': '',
-... }
-
->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
->>> formset.is_valid()
-False
->>> formset.errors
-[{'votes': [u'This field is required.'], 'choice': [u'This field is required.']}, {}]
-
-
-# Displaying more than 1 blank form ###########################################
-
-We can also display more than 1 empty form at a time. To do so, pass a
-extra argument to formset_factory.
-
->>> ChoiceFormSet = formset_factory(Choice, extra=3)
-
->>> formset = ChoiceFormSet(auto_id=False, prefix='choices')
->>> for form in formset.forms:
-... print form.as_ul()
-
Choice:
-
Votes:
-
Choice:
-
Votes:
-
Choice:
-
Votes:
-
-Since we displayed every form as blank, we will also accept them back as blank.
-This may seem a little strange, but later we will show how to require a minimum
-number of forms to be completed.
-
->>> data = {
-... 'choices-TOTAL_FORMS': '3', # the number of forms rendered
-... 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
-... 'choices-MAX_NUM_FORMS': '0', # max number of forms
-... 'choices-0-choice': '',
-... 'choices-0-votes': '',
-... 'choices-1-choice': '',
-... 'choices-1-votes': '',
-... 'choices-2-choice': '',
-... 'choices-2-votes': '',
-... }
-
->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
->>> formset.is_valid()
-True
->>> [form.cleaned_data for form in formset.forms]
-[{}, {}, {}]
-
-
-We can just fill out one of the forms.
-
->>> data = {
-... 'choices-TOTAL_FORMS': '3', # the number of forms rendered
-... 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
-... 'choices-MAX_NUM_FORMS': '0', # max number of forms
-... 'choices-0-choice': 'Calexico',
-... 'choices-0-votes': '100',
-... 'choices-1-choice': '',
-... 'choices-1-votes': '',
-... 'choices-2-choice': '',
-... 'choices-2-votes': '',
-... }
-
->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
->>> formset.is_valid()
-True
->>> [form.cleaned_data for form in formset.forms]
-[{'votes': 100, 'choice': u'Calexico'}, {}, {}]
-
-
-And once again, if we try to partially complete a form, validation will fail.
-
->>> data = {
-... 'choices-TOTAL_FORMS': '3', # the number of forms rendered
-... 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
-... 'choices-MAX_NUM_FORMS': '0', # max number of forms
-... 'choices-0-choice': 'Calexico',
-... 'choices-0-votes': '100',
-... 'choices-1-choice': 'The Decemberists',
-... 'choices-1-votes': '', # missing value
-... 'choices-2-choice': '',
-... 'choices-2-votes': '',
-... }
-
->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
->>> formset.is_valid()
-False
->>> formset.errors
-[{}, {'votes': [u'This field is required.']}, {}]
-
-
-The extra argument also works when the formset is pre-filled with initial
-data.
-
->>> initial = [{'choice': u'Calexico', 'votes': 100}]
->>> formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
->>> for form in formset.forms:
-... print form.as_ul()
-
Choice:
-
Votes:
-
Choice:
-
Votes:
-
Choice:
-
Votes:
-
Choice:
-
Votes:
-
-Make sure retrieving an empty form works, and it shows up in the form list
-
->>> formset.empty_form.empty_permitted
-True
->>> print formset.empty_form.as_ul()
-
Choice:
-
Votes:
-
-# FormSets with deletion ######################################################
-
-We can easily add deletion ability to a FormSet with an argument to
-formset_factory. This will add a boolean field to each form instance. When
-that boolean field is True, the form will be in formset.deleted_forms
-
->>> ChoiceFormSet = formset_factory(Choice, can_delete=True)
-
->>> initial = [{'choice': u'Calexico', 'votes': 100}, {'choice': u'Fergie', 'votes': 900}]
->>> formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
->>> for form in formset.forms:
-... print form.as_ul()
-
Choice:
-
Votes:
-
Delete:
-
Choice:
-
Votes:
-
Delete:
-
Choice:
-
Votes:
-
Delete:
-
-To delete something, we just need to set that form's special delete field to
-'on'. Let's go ahead and delete Fergie.
-
->>> data = {
-... 'choices-TOTAL_FORMS': '3', # the number of forms rendered
-... 'choices-INITIAL_FORMS': '2', # the number of forms with initial data
-... 'choices-MAX_NUM_FORMS': '0', # max number of forms
-... 'choices-0-choice': 'Calexico',
-... 'choices-0-votes': '100',
-... 'choices-0-DELETE': '',
-... 'choices-1-choice': 'Fergie',
-... 'choices-1-votes': '900',
-... 'choices-1-DELETE': 'on',
-... 'choices-2-choice': '',
-... 'choices-2-votes': '',
-... 'choices-2-DELETE': '',
-... }
-
->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
->>> formset.is_valid()
-True
->>> [form.cleaned_data for form in formset.forms]
-[{'votes': 100, 'DELETE': False, 'choice': u'Calexico'}, {'votes': 900, 'DELETE': True, 'choice': u'Fergie'}, {}]
->>> [form.cleaned_data for form in formset.deleted_forms]
-[{'votes': 900, 'DELETE': True, 'choice': u'Fergie'}]
-
-If we fill a form with something and then we check the can_delete checkbox for
-that form, that form's errors should not make the entire formset invalid since
-it's going to be deleted.
-
->>> class CheckForm(Form):
-... field = IntegerField(min_value=100)
-
->>> data = {
-... 'check-TOTAL_FORMS': '3', # the number of forms rendered
-... 'check-INITIAL_FORMS': '2', # the number of forms with initial data
-... 'check-MAX_NUM_FORMS': '0', # max number of forms
-... 'check-0-field': '200',
-... 'check-0-DELETE': '',
-... 'check-1-field': '50',
-... 'check-1-DELETE': 'on',
-... 'check-2-field': '',
-... 'check-2-DELETE': '',
-... }
->>> CheckFormSet = formset_factory(CheckForm, can_delete=True)
->>> formset = CheckFormSet(data, prefix='check')
->>> formset.is_valid()
-True
-
-If we remove the deletion flag now we will have our validation back.
-
->>> data['check-1-DELETE'] = ''
->>> formset = CheckFormSet(data, prefix='check')
->>> formset.is_valid()
-False
-
-Should be able to get deleted_forms from a valid formset even if a
-deleted form would have been invalid.
-
->>> class Person(Form):
-... name = CharField()
-
->>> PeopleForm = formset_factory(
-... form=Person,
-... can_delete=True)
-
->>> p = PeopleForm(
-... {'form-0-name': u'', 'form-0-DELETE': u'on', # no name!
-... 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1,
-... 'form-MAX_NUM_FORMS': 1})
-
->>> p.is_valid()
-True
->>> len(p.deleted_forms)
-1
-
-# FormSets with ordering ######################################################
-
-We can also add ordering ability to a FormSet with an agrument to
-formset_factory. This will add a integer field to each form instance. When
-form validation succeeds, [form.cleaned_data for form in formset.forms] will have the data in the correct
-order specified by the ordering fields. If a number is duplicated in the set
-of ordering fields, for instance form 0 and form 3 are both marked as 1, then
-the form index used as a secondary ordering criteria. In order to put
-something at the front of the list, you'd need to set it's order to 0.
-
->>> ChoiceFormSet = formset_factory(Choice, can_order=True)
-
->>> initial = [{'choice': u'Calexico', 'votes': 100}, {'choice': u'Fergie', 'votes': 900}]
->>> formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
->>> for form in formset.forms:
-... print form.as_ul()
-
Choice:
-
Votes:
-
Order:
-
Choice:
-
Votes:
-
Order:
-
Choice:
-
Votes:
-
Order:
-
->>> data = {
-... 'choices-TOTAL_FORMS': '3', # the number of forms rendered
-... 'choices-INITIAL_FORMS': '2', # the number of forms with initial data
-... 'choices-MAX_NUM_FORMS': '0', # max number of forms
-... 'choices-0-choice': 'Calexico',
-... 'choices-0-votes': '100',
-... 'choices-0-ORDER': '1',
-... 'choices-1-choice': 'Fergie',
-... 'choices-1-votes': '900',
-... 'choices-1-ORDER': '2',
-... 'choices-2-choice': 'The Decemberists',
-... 'choices-2-votes': '500',
-... 'choices-2-ORDER': '0',
-... }
-
->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
->>> formset.is_valid()
-True
->>> for form in formset.ordered_forms:
-... print form.cleaned_data
-{'votes': 500, 'ORDER': 0, 'choice': u'The Decemberists'}
-{'votes': 100, 'ORDER': 1, 'choice': u'Calexico'}
-{'votes': 900, 'ORDER': 2, 'choice': u'Fergie'}
-
-Ordering fields are allowed to be left blank, and if they *are* left blank,
-they will be sorted below everything else.
-
->>> data = {
-... 'choices-TOTAL_FORMS': '4', # the number of forms rendered
-... 'choices-INITIAL_FORMS': '3', # the number of forms with initial data
-... 'choices-MAX_NUM_FORMS': '0', # max number of forms
-... 'choices-0-choice': 'Calexico',
-... 'choices-0-votes': '100',
-... 'choices-0-ORDER': '1',
-... 'choices-1-choice': 'Fergie',
-... 'choices-1-votes': '900',
-... 'choices-1-ORDER': '2',
-... 'choices-2-choice': 'The Decemberists',
-... 'choices-2-votes': '500',
-... 'choices-2-ORDER': '',
-... 'choices-3-choice': 'Basia Bulat',
-... 'choices-3-votes': '50',
-... 'choices-3-ORDER': '',
-... }
-
->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
->>> formset.is_valid()
-True
->>> for form in formset.ordered_forms:
-... print form.cleaned_data
-{'votes': 100, 'ORDER': 1, 'choice': u'Calexico'}
-{'votes': 900, 'ORDER': 2, 'choice': u'Fergie'}
-{'votes': 500, 'ORDER': None, 'choice': u'The Decemberists'}
-{'votes': 50, 'ORDER': None, 'choice': u'Basia Bulat'}
-
-Ordering should work with blank fieldsets.
-
->>> data = {
-... 'choices-TOTAL_FORMS': '3', # the number of forms rendered
-... 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
-... 'choices-MAX_NUM_FORMS': '0', # max number of forms
-... }
-
->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
->>> formset.is_valid()
-True
->>> for form in formset.ordered_forms:
-... print form.cleaned_data
-
-# FormSets with ordering + deletion ###########################################
-
-Let's try throwing ordering and deletion into the same form.
-
->>> ChoiceFormSet = formset_factory(Choice, can_order=True, can_delete=True)
-
->>> initial = [
-... {'choice': u'Calexico', 'votes': 100},
-... {'choice': u'Fergie', 'votes': 900},
-... {'choice': u'The Decemberists', 'votes': 500},
-... ]
->>> formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
->>> for form in formset.forms:
-... print form.as_ul()
-
Choice:
-
Votes:
-
Order:
-
Delete:
-
Choice:
-
Votes:
-
Order:
-
Delete:
-
Choice:
-
Votes:
-
Order:
-
Delete:
-
Choice:
-
Votes:
-
Order:
-
Delete:
-
-Let's delete Fergie, and put The Decemberists ahead of Calexico.
-
->>> data = {
-... 'choices-TOTAL_FORMS': '4', # the number of forms rendered
-... 'choices-INITIAL_FORMS': '3', # the number of forms with initial data
-... 'choices-MAX_NUM_FORMS': '0', # max number of forms
-... 'choices-0-choice': 'Calexico',
-... 'choices-0-votes': '100',
-... 'choices-0-ORDER': '1',
-... 'choices-0-DELETE': '',
-... 'choices-1-choice': 'Fergie',
-... 'choices-1-votes': '900',
-... 'choices-1-ORDER': '2',
-... 'choices-1-DELETE': 'on',
-... 'choices-2-choice': 'The Decemberists',
-... 'choices-2-votes': '500',
-... 'choices-2-ORDER': '0',
-... 'choices-2-DELETE': '',
-... 'choices-3-choice': '',
-... 'choices-3-votes': '',
-... 'choices-3-ORDER': '',
-... 'choices-3-DELETE': '',
-... }
-
->>> formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
->>> formset.is_valid()
-True
->>> for form in formset.ordered_forms:
-... print form.cleaned_data
-{'votes': 500, 'DELETE': False, 'ORDER': 0, 'choice': u'The Decemberists'}
-{'votes': 100, 'DELETE': False, 'ORDER': 1, 'choice': u'Calexico'}
->>> [form.cleaned_data for form in formset.deleted_forms]
-[{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': u'Fergie'}]
-
-Should be able to get ordered forms from a valid formset even if a
-deleted form would have been invalid.
-
->>> class Person(Form):
-... name = CharField()
-
->>> PeopleForm = formset_factory(
-... form=Person,
-... can_delete=True,
-... can_order=True)
-
->>> p = PeopleForm(
-... {'form-0-name': u'', 'form-0-DELETE': u'on', # no name!
-... 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1,
-... 'form-MAX_NUM_FORMS': 1})
-
->>> p.is_valid()
-True
->>> p.ordered_forms
-[]
-
-# FormSet clean hook ##########################################################
-
-FormSets have a hook for doing extra validation that shouldn't be tied to any
-particular form. It follows the same pattern as the clean hook on Forms.
-
-Let's define a FormSet that takes a list of favorite drinks, but raises am
-error if there are any duplicates.
-
->>> class FavoriteDrinkForm(Form):
-... name = CharField()
-...
-
->>> class BaseFavoriteDrinksFormSet(BaseFormSet):
-... def clean(self):
-... seen_drinks = []
-... for drink in self.cleaned_data:
-... if drink['name'] in seen_drinks:
-... raise ValidationError('You may only specify a drink once.')
-... seen_drinks.append(drink['name'])
-...
-
->>> FavoriteDrinksFormSet = formset_factory(FavoriteDrinkForm,
-... formset=BaseFavoriteDrinksFormSet, extra=3)
-
-We start out with a some duplicate data.
-
->>> data = {
-... 'drinks-TOTAL_FORMS': '2', # the number of forms rendered
-... 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data
-... 'drinks-MAX_NUM_FORMS': '0', # max number of forms
-... 'drinks-0-name': 'Gin and Tonic',
-... 'drinks-1-name': 'Gin and Tonic',
-... }
-
->>> formset = FavoriteDrinksFormSet(data, prefix='drinks')
->>> formset.is_valid()
-False
-
-Any errors raised by formset.clean() are available via the
-formset.non_form_errors() method.
-
->>> for error in formset.non_form_errors():
-... print error
-You may only specify a drink once.
-
-
-Make sure we didn't break the valid case.
-
->>> data = {
-... 'drinks-TOTAL_FORMS': '2', # the number of forms rendered
-... 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data
-... 'drinks-MAX_NUM_FORMS': '0', # max number of forms
-... 'drinks-0-name': 'Gin and Tonic',
-... 'drinks-1-name': 'Bloody Mary',
-... }
-
->>> formset = FavoriteDrinksFormSet(data, prefix='drinks')
->>> formset.is_valid()
-True
->>> for error in formset.non_form_errors():
-... print error
-
-# Limiting the maximum number of forms ########################################
-
-# Base case for max_num.
-
-# When not passed, max_num will take its default value of None, i.e. unlimited
-# number of forms, only controlled by the value of the extra parameter.
-
->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3)
->>> formset = LimitedFavoriteDrinkFormSet()
->>> for form in formset.forms:
-... print form
-
Name:
-
Name:
-
Name:
-
-# If max_num is 0 then no form is rendered at all.
-
->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=0)
->>> formset = LimitedFavoriteDrinkFormSet()
->>> for form in formset.forms:
-... print form
-
->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=5, max_num=2)
->>> formset = LimitedFavoriteDrinkFormSet()
->>> for form in formset.forms:
-... print form
-
Name:
-
Name:
-
-# Ensure that max_num has no effect when extra is less than max_num.
-
->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2)
->>> formset = LimitedFavoriteDrinkFormSet()
->>> for form in formset.forms:
-... print form
-
Name:
-
-# max_num with initial data
-
-# When not passed, max_num will take its default value of None, i.e. unlimited
-# number of forms, only controlled by the values of the initial and extra
-# parameters.
-
->>> initial = [
-... {'name': 'Fernet and Coke'},
-... ]
->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1)
->>> formset = LimitedFavoriteDrinkFormSet(initial=initial)
->>> for form in formset.forms:
-... print form
-
Name:
-
Name:
-
-# If max_num is 0 then no form is rendered at all, even if extra and initial
-# are specified.
-
->>> initial = [
-... {'name': 'Fernet and Coke'},
-... {'name': 'Bloody Mary'},
-... ]
->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=0)
->>> formset = LimitedFavoriteDrinkFormSet(initial=initial)
->>> for form in formset.forms:
-... print form
-
-# More initial forms than max_num will result in only the first max_num of
-# them to be displayed with no extra forms.
-
->>> initial = [
-... {'name': 'Gin Tonic'},
-... {'name': 'Bloody Mary'},
-... {'name': 'Jack and Coke'},
-... ]
->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2)
->>> formset = LimitedFavoriteDrinkFormSet(initial=initial)
->>> for form in formset.forms:
-... print form
-
Name:
-
Name:
-
-# One form from initial and extra=3 with max_num=2 should result in the one
-# initial form and one extra.
-
->>> initial = [
-... {'name': 'Gin Tonic'},
-... ]
->>> LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=2)
->>> formset = LimitedFavoriteDrinkFormSet(initial=initial)
->>> for form in formset.forms:
-... print form
-
Name:
-
Name:
-
-
-# Regression test for #6926 ##################################################
-
-Make sure the management form has the correct prefix.
-
->>> formset = FavoriteDrinksFormSet()
->>> formset.management_form.prefix
-'form'
-
->>> formset = FavoriteDrinksFormSet(data={})
->>> formset.management_form.prefix
-'form'
-
->>> formset = FavoriteDrinksFormSet(initial={})
->>> formset.management_form.prefix
-'form'
-
-# Regression test for #12878 #################################################
-
->>> data = {
-... 'drinks-TOTAL_FORMS': '2', # the number of forms rendered
-... 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data
-... 'drinks-MAX_NUM_FORMS': '0', # max number of forms
-... 'drinks-0-name': 'Gin and Tonic',
-... 'drinks-1-name': 'Gin and Tonic',
-... }
-
->>> formset = FavoriteDrinksFormSet(data, prefix='drinks')
->>> formset.is_valid()
-False
->>> print formset.non_form_errors()
-
You may only specify a drink once.
-
-"""
-
-data = {
- 'choices-TOTAL_FORMS': '1', # the number of forms rendered
- 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
- 'choices-MAX_NUM_FORMS': '0', # max number of forms
- 'choices-0-choice': 'Calexico',
- 'choices-0-votes': '100',
-}
-
-class Choice(Form):
- choice = CharField()
- votes = IntegerField()
-
-ChoiceFormSet = formset_factory(Choice)
-
-class FormsetAsFooTests(TestCase):
- def test_as_table(self):
- formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
- self.assertEqual(formset.as_table(),"""
-
""")
-
diff --git a/tests/regressiontests/forms/input_formats.py b/tests/regressiontests/forms/input_formats.py
deleted file mode 100644
index e362620ddb..0000000000
--- a/tests/regressiontests/forms/input_formats.py
+++ /dev/null
@@ -1,894 +0,0 @@
-from datetime import time, date, datetime
-
-from django import forms
-from django.conf import settings
-from django.utils.translation import activate, deactivate
-from django.utils.unittest import TestCase
-
-
-class LocalizedTimeTests(TestCase):
- def setUp(self):
- self.old_TIME_INPUT_FORMATS = settings.TIME_INPUT_FORMATS
- self.old_USE_L10N = settings.USE_L10N
-
- settings.TIME_INPUT_FORMATS = ["%I:%M:%S %p", "%I:%M %p"]
- settings.USE_L10N = True
-
- activate('de')
-
- def tearDown(self):
- settings.TIME_INPUT_FORMATS = self.old_TIME_INPUT_FORMATS
- settings.USE_L10N = self.old_USE_L10N
-
- 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")
-
-
-class CustomTimeInputFormatsTests(TestCase):
- def setUp(self):
- self.old_TIME_INPUT_FORMATS = settings.TIME_INPUT_FORMATS
- settings.TIME_INPUT_FORMATS = ["%I:%M:%S %p", "%I:%M %p"]
-
- def tearDown(self):
- settings.TIME_INPUT_FORMATS = self.old_TIME_INPUT_FORMATS
-
- 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(TestCase):
- 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")
-
-
-class LocalizedDateTests(TestCase):
- def setUp(self):
- self.old_DATE_INPUT_FORMATS = settings.DATE_INPUT_FORMATS
- self.old_USE_L10N = settings.USE_L10N
-
- settings.DATE_INPUT_FORMATS = ["%d/%m/%Y", "%d-%m-%Y"]
- settings.USE_L10N = True
-
- activate('de')
-
- def tearDown(self):
- settings.DATE_INPUT_FORMATS = self.old_DATE_INPUT_FORMATS
- settings.USE_L10N = self.old_USE_L10N
-
- 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')
-
- # 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")
-
-class CustomDateInputFormatsTests(TestCase):
- def setUp(self):
- self.old_DATE_INPUT_FORMATS = settings.DATE_INPUT_FORMATS
- settings.DATE_INPUT_FORMATS = ["%d.%m.%Y", "%d-%m-%Y"]
-
- def tearDown(self):
- settings.DATE_INPUT_FORMATS = self.old_DATE_INPUT_FORMATS
-
- 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(TestCase):
- 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")
-
-class LocalizedDateTimeTests(TestCase):
- def setUp(self):
- self.old_DATETIME_INPUT_FORMATS = settings.DATETIME_INPUT_FORMATS
- self.old_USE_L10N = settings.USE_L10N
-
- settings.DATETIME_INPUT_FORMATS = ["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"]
- settings.USE_L10N = True
-
- activate('de')
-
- def tearDown(self):
- settings.DATETIME_INPUT_FORMATS = self.old_DATETIME_INPUT_FORMATS
- settings.USE_L10N = self.old_USE_L10N
-
- 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')
-
- # 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")
-
-
-class CustomDateTimeInputFormatsTests(TestCase):
- def setUp(self):
- self.old_DATETIME_INPUT_FORMATS = settings.DATETIME_INPUT_FORMATS
- settings.DATETIME_INPUT_FORMATS = ["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"]
-
- def tearDown(self):
- settings.DATETIME_INPUT_FORMATS = self.old_DATETIME_INPUT_FORMATS
-
- 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(TestCase):
- 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/regressiontests/forms/localflavor/be.py b/tests/regressiontests/forms/localflavor/be.py
index 8789d9f89d..2eefc59af9 100644
--- a/tests/regressiontests/forms/localflavor/be.py
+++ b/tests/regressiontests/forms/localflavor/be.py
@@ -51,7 +51,7 @@ class BETests(TestCase):
self.assertEqual(u'0412.34.56.78', f.clean('0412.34.56.78'))
self.assertEqual(u'012345678', f.clean('012345678'))
self.assertEqual(u'0412345678', f.clean('0412345678'))
- err_message = "[u'Enter a valid phone number in one of the formats 0x xxx xx xx, 0xx xx xx xx, 04xx xx xx xx, 0x/xxx.xx.xx, 0xx/xx.xx.xx, 04xx/xx.xx.xx, 0xxxxxxxx, 04xxxxxxxx, 0x.xxx.xx.xx, 0xx.xx.xx.xx, 04xx.xx.xx.xx.']"
+ err_message = "[u'Enter a valid phone number in one of the formats 0x xxx xx xx, 0xx xx xx xx, 04xx xx xx xx, 0x/xxx.xx.xx, 0xx/xx.xx.xx, 04xx/xx.xx.xx, 0x.xxx.xx.xx, 0xx.xx.xx.xx, 04xx.xx.xx.xx, 0xxxxxxxx or 04xxxxxxxx.']"
self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '01234567')
self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '12/345.67.89')
self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '012/345.678.90')
@@ -75,7 +75,7 @@ class BETests(TestCase):
self.assertEqual(u'012345678', f.clean('012345678'))
self.assertEqual(u'0412345678', f.clean('0412345678'))
self.assertEqual(u'', f.clean(''))
- err_message = "[u'Enter a valid phone number in one of the formats 0x xxx xx xx, 0xx xx xx xx, 04xx xx xx xx, 0x/xxx.xx.xx, 0xx/xx.xx.xx, 04xx/xx.xx.xx, 0xxxxxxxx, 04xxxxxxxx, 0x.xxx.xx.xx, 0xx.xx.xx.xx, 04xx.xx.xx.xx.']"
+ err_message = "[u'Enter a valid phone number in one of the formats 0x xxx xx xx, 0xx xx xx xx, 04xx xx xx xx, 0x/xxx.xx.xx, 0xx/xx.xx.xx, 04xx/xx.xx.xx, 0x.xxx.xx.xx, 0xx.xx.xx.xx, 04xx.xx.xx.xx, 0xxxxxxxx or 04xxxxxxxx.']"
self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '01234567')
self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '12/345.67.89')
self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '012/345.678.90')
@@ -85,10 +85,10 @@ class BETests(TestCase):
self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '012/34 56 789')
self.assertRaisesErrorWithMessage(ValidationError, err_message, f.clean, '012.34 56 789')
- def test_phone_number_field(self):
+ def test_region_field(self):
w = BERegionSelect()
self.assertEqual(u'', w.render('regions', 'VLG'))
- def test_phone_number_field(self):
+ def test_province_field(self):
w = BEProvinceSelect()
self.assertEqual(u'', w.render('provinces', 'WLG'))
diff --git a/tests/regressiontests/forms/localflavortests.py b/tests/regressiontests/forms/localflavortests.py
new file mode 100644
index 0000000000..30c06ef79a
--- /dev/null
+++ b/tests/regressiontests/forms/localflavortests.py
@@ -0,0 +1,69 @@
+# -*- coding: utf-8 -*-
+from localflavor.ar import tests as localflavor_ar_tests
+from localflavor.at import tests as localflavor_at_tests
+from localflavor.au import tests as localflavor_au_tests
+from localflavor.br import tests as localflavor_br_tests
+from localflavor.ca import tests as localflavor_ca_tests
+from localflavor.ch import tests as localflavor_ch_tests
+from localflavor.cl import tests as localflavor_cl_tests
+from localflavor.cz import tests as localflavor_cz_tests
+from localflavor.de import tests as localflavor_de_tests
+from localflavor.es import tests as localflavor_es_tests
+from localflavor.fi import tests as localflavor_fi_tests
+from localflavor.fr import tests as localflavor_fr_tests
+from localflavor.generic import tests as localflavor_generic_tests
+from localflavor.id import tests as localflavor_id_tests
+from localflavor.ie import tests as localflavor_ie_tests
+from localflavor.il import IsraelLocalFlavorTests
+from localflavor.is_ import tests as localflavor_is_tests
+from localflavor.it import tests as localflavor_it_tests
+from localflavor.jp import tests as localflavor_jp_tests
+from localflavor.kw import tests as localflavor_kw_tests
+from localflavor.nl import tests as localflavor_nl_tests
+from localflavor.pl import tests as localflavor_pl_tests
+from localflavor.pt import tests as localflavor_pt_tests
+from localflavor.ro import tests as localflavor_ro_tests
+from localflavor.se import tests as localflavor_se_tests
+from localflavor.sk import tests as localflavor_sk_tests
+from localflavor.uk import tests as localflavor_uk_tests
+from localflavor.us import tests as localflavor_us_tests
+from localflavor.uy import tests as localflavor_uy_tests
+from localflavor.za import tests as localflavor_za_tests
+
+from localflavor.be import BETests
+
+__test__ = {
+ 'localflavor_ar_tests': localflavor_ar_tests,
+ 'localflavor_at_tests': localflavor_at_tests,
+ 'localflavor_au_tests': localflavor_au_tests,
+ 'localflavor_br_tests': localflavor_br_tests,
+ 'localflavor_ca_tests': localflavor_ca_tests,
+ 'localflavor_ch_tests': localflavor_ch_tests,
+ 'localflavor_cl_tests': localflavor_cl_tests,
+ 'localflavor_cz_tests': localflavor_cz_tests,
+ 'localflavor_de_tests': localflavor_de_tests,
+ 'localflavor_es_tests': localflavor_es_tests,
+ 'localflavor_fi_tests': localflavor_fi_tests,
+ 'localflavor_fr_tests': localflavor_fr_tests,
+ 'localflavor_generic_tests': localflavor_generic_tests,
+ 'localflavor_id_tests': localflavor_id_tests,
+ 'localflavor_ie_tests': localflavor_ie_tests,
+ 'localflavor_is_tests': localflavor_is_tests,
+ 'localflavor_it_tests': localflavor_it_tests,
+ 'localflavor_jp_tests': localflavor_jp_tests,
+ 'localflavor_kw_tests': localflavor_kw_tests,
+ 'localflavor_nl_tests': localflavor_nl_tests,
+ 'localflavor_pl_tests': localflavor_pl_tests,
+ 'localflavor_pt_tests': localflavor_pt_tests,
+ 'localflavor_ro_tests': localflavor_ro_tests,
+ 'localflavor_se_tests': localflavor_se_tests,
+ 'localflavor_sk_tests': localflavor_sk_tests,
+ 'localflavor_uk_tests': localflavor_uk_tests,
+ 'localflavor_us_tests': localflavor_us_tests,
+ 'localflavor_uy_tests': localflavor_uy_tests,
+ 'localflavor_za_tests': localflavor_za_tests,
+}
+
+if __name__ == "__main__":
+ import doctest
+ doctest.testmod()
diff --git a/tests/regressiontests/forms/media.py b/tests/regressiontests/forms/media.py
deleted file mode 100644
index d715fb4d80..0000000000
--- a/tests/regressiontests/forms/media.py
+++ /dev/null
@@ -1,385 +0,0 @@
-# -*- coding: utf-8 -*-
-# Tests for the media handling on widgets and forms
-
-media_tests = r"""
->>> from django.forms import TextInput, Media, TextInput, CharField, Form, MultiWidget
->>> from django.conf import settings
->>> ORIGINAL_MEDIA_URL = settings.MEDIA_URL
->>> settings.MEDIA_URL = 'http://media.example.com/media/'
-
-# Check construction of media objects
->>> m = Media(css={'all': ('path/to/css1','/path/to/css2')}, js=('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3'))
->>> print m
-
-
-
-
-
-
->>> class Foo:
-... css = {
-... 'all': ('path/to/css1','/path/to/css2')
-... }
-... js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3')
->>> m3 = Media(Foo)
->>> print m3
-
-
-
-
-
-
->>> m3 = Media(Foo)
->>> print m3
-
-
-
-
-
-
-# A widget can exist without a media definition
->>> class MyWidget(TextInput):
-... pass
-
->>> w = MyWidget()
->>> print w.media
-
-
-###############################################################
-# DSL Class-based media definitions
-###############################################################
-
-# A widget can define media if it needs to.
-# Any absolute path will be preserved; relative paths are combined
-# with the value of settings.MEDIA_URL
->>> class MyWidget1(TextInput):
-... class Media:
-... css = {
-... 'all': ('path/to/css1','/path/to/css2')
-... }
-... js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3')
-
->>> w1 = MyWidget1()
->>> print w1.media
-
-
-
-
-
-
-# Media objects can be interrogated by media type
->>> print w1.media['css']
-
-
-
->>> print w1.media['js']
-
-
-
-
-# Media objects can be combined. Any given media resource will appear only
-# once. Duplicated media definitions are ignored.
->>> class MyWidget2(TextInput):
-... class Media:
-... css = {
-... 'all': ('/path/to/css2','/path/to/css3')
-... }
-... js = ('/path/to/js1','/path/to/js4')
-
->>> class MyWidget3(TextInput):
-... class Media:
-... css = {
-... 'all': ('/path/to/css3','path/to/css1')
-... }
-... js = ('/path/to/js1','/path/to/js4')
-
->>> w2 = MyWidget2()
->>> w3 = MyWidget3()
->>> print w1.media + w2.media + w3.media
-
-
-
-
-
-
-
-
-# Check that media addition hasn't affected the original objects
->>> print w1.media
-
-
-
-
-
-
-# Regression check for #12879: specifying the same CSS or JS file
-# multiple times in a single Media instance should result in that file
-# only being included once.
->>> class MyWidget4(TextInput):
-... class Media:
-... css = {'all': ('/path/to/css1', '/path/to/css1')}
-... js = ('/path/to/js1', '/path/to/js1')
-
->>> w4 = MyWidget4()
->>> print w4.media
-
-
-
-
-###############################################################
-# Property-based media definitions
-###############################################################
-
-# Widget media can be defined as a property
->>> class MyWidget4(TextInput):
-... def _media(self):
-... return Media(css={'all': ('/some/path',)}, js = ('/some/js',))
-... media = property(_media)
-
->>> w4 = MyWidget4()
->>> print w4.media
-
-
-
-# Media properties can reference the media of their parents
->>> class MyWidget5(MyWidget4):
-... def _media(self):
-... return super(MyWidget5, self).media + Media(css={'all': ('/other/path',)}, js = ('/other/js',))
-... media = property(_media)
-
->>> w5 = MyWidget5()
->>> print w5.media
-
-
-
-
-
-# Media properties can reference the media of their parents,
-# even if the parent media was defined using a class
->>> class MyWidget6(MyWidget1):
-... def _media(self):
-... return super(MyWidget6, self).media + Media(css={'all': ('/other/path',)}, js = ('/other/js',))
-... media = property(_media)
-
->>> w6 = MyWidget6()
->>> print w6.media
-
-
-
-
-
-
-
-
-###############################################################
-# Inheritance of media
-###############################################################
-
-# If a widget extends another but provides no media definition, it inherits the parent widget's media
->>> class MyWidget7(MyWidget1):
-... pass
-
->>> w7 = MyWidget7()
->>> print w7.media
-
-
-
-
-
-
-# If a widget extends another but defines media, it extends the parent widget's media by default
->>> class MyWidget8(MyWidget1):
-... class Media:
-... css = {
-... 'all': ('/path/to/css3','path/to/css1')
-... }
-... js = ('/path/to/js1','/path/to/js4')
-
->>> w8 = MyWidget8()
->>> print w8.media
-
-
-
-
-
-
-
-
-# If a widget extends another but defines media, it extends the parents widget's media,
-# even if the parent defined media using a property.
->>> class MyWidget9(MyWidget4):
-... class Media:
-... css = {
-... 'all': ('/other/path',)
-... }
-... js = ('/other/js',)
-
->>> w9 = MyWidget9()
->>> print w9.media
-
-
-
-
-
-# A widget can disable media inheritance by specifying 'extend=False'
->>> class MyWidget10(MyWidget1):
-... class Media:
-... extend = False
-... css = {
-... 'all': ('/path/to/css3','path/to/css1')
-... }
-... js = ('/path/to/js1','/path/to/js4')
-
->>> w10 = MyWidget10()
->>> print w10.media
-
-
-
-
-
-# A widget can explicitly enable full media inheritance by specifying 'extend=True'
->>> class MyWidget11(MyWidget1):
-... class Media:
-... extend = True
-... css = {
-... 'all': ('/path/to/css3','path/to/css1')
-... }
-... js = ('/path/to/js1','/path/to/js4')
-
->>> w11 = MyWidget11()
->>> print w11.media
-
-
-
-
-
-
-
-
-# A widget can enable inheritance of one media type by specifying extend as a tuple
->>> class MyWidget12(MyWidget1):
-... class Media:
-... extend = ('css',)
-... css = {
-... 'all': ('/path/to/css3','path/to/css1')
-... }
-... js = ('/path/to/js1','/path/to/js4')
-
->>> w12 = MyWidget12()
->>> print w12.media
-
-
-
-
-
-
-###############################################################
-# Multi-media handling for CSS
-###############################################################
-
-# A widget can define CSS media for multiple output media types
->>> class MultimediaWidget(TextInput):
-... class Media:
-... css = {
-... 'screen, print': ('/file1','/file2'),
-... 'screen': ('/file3',),
-... 'print': ('/file4',)
-... }
-... js = ('/path/to/js1','/path/to/js4')
-
->>> multimedia = MultimediaWidget()
->>> print multimedia.media
-
-
-
-
-
-
-
-###############################################################
-# Multiwidget media handling
-###############################################################
-
-# MultiWidgets have a default media definition that gets all the
-# media from the component widgets
->>> class MyMultiWidget(MultiWidget):
-... def __init__(self, attrs=None):
-... widgets = [MyWidget1, MyWidget2, MyWidget3]
-... super(MyMultiWidget, self).__init__(widgets, attrs)
-
->>> mymulti = MyMultiWidget()
->>> print mymulti.media
-
-
-
-
-
-
-
-
-###############################################################
-# Media processing for forms
-###############################################################
-
-# You can ask a form for the media required by its widgets.
->>> class MyForm(Form):
-... field1 = CharField(max_length=20, widget=MyWidget1())
-... field2 = CharField(max_length=20, widget=MyWidget2())
->>> f1 = MyForm()
->>> print f1.media
-
-
-
-
-
-
-
-
-# Form media can be combined to produce a single media definition.
->>> class AnotherForm(Form):
-... field3 = CharField(max_length=20, widget=MyWidget3())
->>> f2 = AnotherForm()
->>> print f1.media + f2.media
-
-
-
-
-
-
-
-
-# Forms can also define media, following the same rules as widgets.
->>> class FormWithMedia(Form):
-... field1 = CharField(max_length=20, widget=MyWidget1())
-... field2 = CharField(max_length=20, widget=MyWidget2())
-... class Media:
-... js = ('/some/form/javascript',)
-... css = {
-... 'all': ('/some/form/css',)
-... }
->>> f3 = FormWithMedia()
->>> print f3.media
-
-
-
-
-
-
-
-
-
-
-# Media works in templates
->>> from django.template import Template, Context
->>> Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3}))
-u'
-
-
-
-
-
-
-'
-
->>> settings.MEDIA_URL = ORIGINAL_MEDIA_URL
-"""
diff --git a/tests/regressiontests/forms/models.py b/tests/regressiontests/forms/models.py
index a4891df06e..0a0fea45ad 100644
--- a/tests/regressiontests/forms/models.py
+++ b/tests/regressiontests/forms/models.py
@@ -1,14 +1,9 @@
# -*- coding: utf-8 -*-
import datetime
-import shutil
import tempfile
from django.db import models
-# Can't import as "forms" due to implementation details in the test suite (the
-# current file is called "forms" and is already imported).
-from django import forms as django_forms
from django.core.files.storage import FileSystemStorage
-from django.test import TestCase
temp_storage_location = tempfile.mkdtemp()
temp_storage = FileSystemStorage(location=temp_storage_location)
@@ -56,182 +51,11 @@ class ChoiceFieldModel(models.Model):
multi_choice_int = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='multi_choice_int',
default=lambda: [1])
-class ChoiceFieldForm(django_forms.ModelForm):
- class Meta:
- model = ChoiceFieldModel
-
class FileModel(models.Model):
file = models.FileField(storage=temp_storage, upload_to='tests')
-class FileForm(django_forms.Form):
- file1 = django_forms.FileField()
-
class Group(models.Model):
name = models.CharField(max_length=10)
def __unicode__(self):
return u'%s' % self.name
-
-class TestTicket12510(TestCase):
- ''' It is not necessary to generate choices for ModelChoiceField (regression test for #12510). '''
- def setUp(self):
- self.groups = [Group.objects.create(name=name) for name in 'abc']
-
- def test_choices_not_fetched_when_not_rendering(self):
- def test():
- field = django_forms.ModelChoiceField(Group.objects.order_by('-name'))
- self.assertEqual('a', field.clean(self.groups[0].pk).name)
- # only one query is required to pull the model from DB
- self.assertNumQueries(1, test)
-
-class ModelFormCallableModelDefault(TestCase):
- def test_no_empty_option(self):
- "If a model's ForeignKey has blank=False and a default, no empty option is created (Refs #10792)."
- option = ChoiceOptionModel.objects.create(name='default')
-
- choices = list(ChoiceFieldForm().fields['choice'].choices)
- self.assertEquals(len(choices), 1)
- self.assertEquals(choices[0], (option.pk, unicode(option)))
-
- def test_callable_initial_value(self):
- "The initial value for a callable default returning a queryset is the pk (refs #13769)"
- obj1 = ChoiceOptionModel.objects.create(id=1, name='default')
- obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2')
- obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3')
- self.assertEquals(ChoiceFieldForm().as_p(), """
Choice:
-
Choice int:
-
Multi choice: Hold down "Control", or "Command" on a Mac, to select more than one.
-
Multi choice int: Hold down "Control", or "Command" on a Mac, to select more than one.
Multi choice:
- Hold down "Control", or "Command" on a Mac, to select more than one.
-
Multi choice int:
- Hold down "Control", or "Command" on a Mac, to select more than one.
""")
-
-
-__test__ = {'API_TESTS': """
->>> from django.forms.models import ModelForm
->>> from django.core.files.uploadedfile import SimpleUploadedFile
-
-# FileModel with unicode filename and data #########################
->>> f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')}, auto_id=False)
->>> f.is_valid()
-True
->>> f.cleaned_data
-{'file1': }
->>> m = FileModel.objects.create(file=f.cleaned_data['file1'])
-
-# It's enough that m gets created without error. Preservation of the exotic name is checked
-# in a file_uploads test; it's hard to do that correctly with doctest's unicode issues. So
-# we create and then immediately delete m so as to not leave the exotically named file around
-# for shutil.rmtree (on Windows) to have trouble with later.
->>> m.delete()
-
-# Boundary conditions on a PostitiveIntegerField #########################
->>> class BoundaryForm(ModelForm):
-... class Meta:
-... model = BoundaryModel
->>> f = BoundaryForm({'positive_integer': 100})
->>> f.is_valid()
-True
->>> f = BoundaryForm({'positive_integer': 0})
->>> f.is_valid()
-True
->>> f = BoundaryForm({'positive_integer': -100})
->>> f.is_valid()
-False
-
-# Formfield initial values ########
-If the model has default values for some fields, they are used as the formfield
-initial values.
->>> class DefaultsForm(ModelForm):
-... class Meta:
-... model = Defaults
->>> DefaultsForm().fields['name'].initial
-u'class default value'
->>> DefaultsForm().fields['def_date'].initial
-datetime.date(1980, 1, 1)
->>> DefaultsForm().fields['value'].initial
-42
->>> r1 = DefaultsForm()['callable_default'].as_widget()
->>> r2 = DefaultsForm()['callable_default'].as_widget()
->>> r1 == r2
-False
-
-In a ModelForm that is passed an instance, the initial values come from the
-instance's values, not the model's defaults.
->>> foo_instance = Defaults(name=u'instance value', def_date=datetime.date(1969, 4, 4), value=12)
->>> instance_form = DefaultsForm(instance=foo_instance)
->>> instance_form.initial['name']
-u'instance value'
->>> instance_form.initial['def_date']
-datetime.date(1969, 4, 4)
->>> instance_form.initial['value']
-12
-
->>> from django.forms import CharField
->>> class ExcludingForm(ModelForm):
-... name = CharField(max_length=255)
-... class Meta:
-... model = Defaults
-... exclude = ['name', 'callable_default']
->>> f = ExcludingForm({'name': u'Hello', 'value': 99, 'def_date': datetime.date(1999, 3, 2)})
->>> f.is_valid()
-True
->>> f.cleaned_data['name']
-u'Hello'
->>> obj = f.save()
->>> obj.name
-u'class default value'
->>> obj.value
-99
->>> obj.def_date
-datetime.date(1999, 3, 2)
->>> shutil.rmtree(temp_storage_location)
-
-
-"""}
diff --git a/tests/regressiontests/forms/regressions.py b/tests/regressiontests/forms/regressions.py
deleted file mode 100644
index 9471932057..0000000000
--- a/tests/regressiontests/forms/regressions.py
+++ /dev/null
@@ -1,135 +0,0 @@
-# -*- coding: utf-8 -*-
-# Tests to prevent against recurrences of earlier bugs.
-
-tests = r"""
-It should be possible to re-use attribute dictionaries (#3810)
->>> from django.forms import *
->>> extra_attrs = {'class': 'special'}
->>> class TestForm(Form):
-... f1 = CharField(max_length=10, widget=TextInput(attrs=extra_attrs))
-... f2 = CharField(widget=TextInput(attrs=extra_attrs))
->>> TestForm(auto_id=False).as_p()
-u'
F1:
\n
F2:
'
-
-#######################
-# Tests for form i18n #
-#######################
-There were some problems with form translations in #3600
-
->>> from django.utils.translation import ugettext_lazy, activate, deactivate
->>> class SomeForm(Form):
-... username = CharField(max_length=10, label=ugettext_lazy('Username'))
->>> f = SomeForm()
->>> print f.as_p()
-
Username:
-
-Translations are done at rendering time, so multi-lingual apps can define forms
-early and still send back the right translation.
-
->>> activate('de')
->>> print f.as_p()
-
Benutzername:
->>> activate('pl')
->>> f.as_p()
-u'
Nazwa u\u017cytkownika:
'
->>> deactivate()
-
-There was some problems with form translations in #5216
->>> class SomeForm(Form):
-... field_1 = CharField(max_length=10, label=ugettext_lazy('field_1'))
-... field_2 = CharField(max_length=10, label=ugettext_lazy('field_2'), widget=TextInput(attrs={'id': 'field_2_id'}))
->>> f = SomeForm()
->>> print f['field_1'].label_tag()
-field_1
->>> print f['field_2'].label_tag()
-field_2
-
-Unicode decoding problems...
->>> GENDERS = ((u'\xc5', u'En tied\xe4'), (u'\xf8', u'Mies'), (u'\xdf', u'Nainen'))
->>> class SomeForm(Form):
-... somechoice = ChoiceField(choices=GENDERS, widget=RadioSelect(), label=u'\xc5\xf8\xdf')
->>> f = SomeForm()
->>> f.as_p()
-u'
\xc5\xf8\xdf:
\n
En tied\xe4
\n
Mies
\n
Nainen
\n
'
-
-Testing choice validation with UTF-8 bytestrings as input (these are the
-Russian abbreviations "мес." and "шт.".
-
->>> UNITS = (('\xd0\xbc\xd0\xb5\xd1\x81.', '\xd0\xbc\xd0\xb5\xd1\x81.'), ('\xd1\x88\xd1\x82.', '\xd1\x88\xd1\x82.'))
->>> f = ChoiceField(choices=UNITS)
->>> f.clean(u'\u0448\u0442.')
-u'\u0448\u0442.'
->>> f.clean('\xd1\x88\xd1\x82.')
-u'\u0448\u0442.'
-
-Translated error messages used to be buggy.
->>> activate('ru')
->>> f = SomeForm({})
->>> f.as_p()
-u'
'
->>> deactivate()
-
-Deep copying translated text shouldn't raise an error
->>> from django.utils.translation import gettext_lazy
->>> class CopyForm(Form):
-... degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),)))
->>> f = CopyForm()
-
-#######################
-# Miscellaneous Tests #
-#######################
-
-There once was a problem with Form fields called "data". Let's make sure that
-doesn't come back.
->>> class DataForm(Form):
-... data = CharField(max_length=10)
->>> f = DataForm({'data': 'xyzzy'})
->>> f.is_valid()
-True
->>> f.cleaned_data
-{'data': u'xyzzy'}
-
-A form with *only* hidden fields that has errors is going to be very unusual.
-But we can try to make sure it doesn't generate invalid XHTML. In this case,
-the as_p() method is the tricky one, since error lists cannot be nested
-(validly) inside p elements.
-
->>> class HiddenForm(Form):
-... data = IntegerField(widget=HiddenInput)
->>> f = HiddenForm({})
->>> f.as_p()
-u'
(Hidden field data) This field is required.
\n
'
->>> f.as_table()
-u'
(Hidden field data) This field is required.
'
-
-###################################################
-# 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': '",
+ 'special_safe_name': "Do not escape"
+ }, auto_id=False)
+ self.assertEqual(f.as_table(), """
<em>Special</em> Field:
Something's wrong with 'Should escape < & > and <script>alert('xss')</script>'
+
Special Field:
'Do not escape' is a safe string
""")
+
+ def test_validating_multiple_fields(self):
+ # There are a couple of ways to do multiple-field validation. If you want the
+ # validation message to be associated with a particular field, implement the
+ # clean_XXX() method on the Form, where XXX is the field name. As in
+ # Field.clean(), the clean_XXX() method should return the cleaned value. In the
+ # clean_XXX() method, you have access to self.cleaned_data, which is a dictionary
+ # of all the data that has been cleaned *so far*, in order by the fields,
+ # including the current field (e.g., the field XXX if you're in clean_XXX()).
+ class UserRegistration(Form):
+ username = CharField(max_length=10)
+ password1 = CharField(widget=PasswordInput)
+ password2 = CharField(widget=PasswordInput)
+
+ def clean_password2(self):
+ if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
+ raise ValidationError(u'Please make sure your passwords match.')
+
+ return self.cleaned_data['password2']
+
+ f = UserRegistration(auto_id=False)
+ self.assertEqual(f.errors, {})
+ f = UserRegistration({}, auto_id=False)
+ self.assertEqual(f.errors['username'], [u'This field is required.'])
+ self.assertEqual(f.errors['password1'], [u'This field is required.'])
+ self.assertEqual(f.errors['password2'], [u'This field is required.'])
+ f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
+ self.assertEqual(f.errors['password2'], [u'Please make sure your passwords match.'])
+ f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
+ self.assertEqual(f.errors, {})
+ self.assertEqual(f.cleaned_data['username'], u'adrian')
+ self.assertEqual(f.cleaned_data['password1'], u'foo')
+ self.assertEqual(f.cleaned_data['password2'], u'foo')
+
+ # Another way of doing multiple-field validation is by implementing the
+ # Form's clean() method. If you do this, any ValidationError raised by that
+ # method will not be associated with a particular field; it will have a
+ # special-case association with the field named '__all__'.
+ # Note that in Form.clean(), you have access to self.cleaned_data, a dictionary of
+ # all the fields/values that have *not* raised a ValidationError. Also note
+ # Form.clean() is required to return a dictionary of all clean data.
+ class UserRegistration(Form):
+ username = CharField(max_length=10)
+ password1 = CharField(widget=PasswordInput)
+ password2 = CharField(widget=PasswordInput)
+
+ def clean(self):
+ if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
+ raise ValidationError(u'Please make sure your passwords match.')
+
+ return self.cleaned_data
+
+ f = UserRegistration(auto_id=False)
+ self.assertEqual(f.errors, {})
+ f = UserRegistration({}, auto_id=False)
+ self.assertEqual(f.as_table(), """
Username:
This field is required.
+
Password1:
This field is required.
+
Password2:
This field is required.
""")
+ self.assertEqual(f.errors['username'], [u'This field is required.'])
+ self.assertEqual(f.errors['password1'], [u'This field is required.'])
+ self.assertEqual(f.errors['password2'], [u'This field is required.'])
+ f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
+ self.assertEqual(f.errors['__all__'], [u'Please make sure your passwords match.'])
+ self.assertEqual(f.as_table(), """
Please make sure your passwords match.
+
Username:
+
Password1:
+
Password2:
""")
+ self.assertEqual(f.as_ul(), """
Please make sure your passwords match.
+
Username:
+
Password1:
+
Password2:
""")
+ f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
+ self.assertEqual(f.errors, {})
+ self.assertEqual(f.cleaned_data['username'], u'adrian')
+ self.assertEqual(f.cleaned_data['password1'], u'foo')
+ self.assertEqual(f.cleaned_data['password2'], u'foo')
+
+ def test_dynamic_construction(self):
+ # It's possible to construct a Form dynamically by adding to the self.fields
+ # dictionary in __init__(). Don't forget to call Form.__init__() within the
+ # subclass' __init__().
+ class Person(Form):
+ first_name = CharField()
+ last_name = CharField()
+
+ def __init__(self, *args, **kwargs):
+ super(Person, self).__init__(*args, **kwargs)
+ self.fields['birthday'] = DateField()
+
+ p = Person(auto_id=False)
+ self.assertEqual(p.as_table(), """
First name:
+
Last name:
+
Birthday:
""")
+
+ # Instances of a dynamic Form do not persist fields from one Form instance to
+ # the next.
+ class MyForm(Form):
+ def __init__(self, data=None, auto_id=False, field_list=[]):
+ Form.__init__(self, data, auto_id=auto_id)
+
+ for field in field_list:
+ self.fields[field[0]] = field[1]
+
+ field_list = [('field1', CharField()), ('field2', CharField())]
+ my_form = MyForm(field_list=field_list)
+ self.assertEqual(my_form.as_table(), """
""")
+
+ # Similarly, changes to field attributes do not persist from one Form instance
+ # to the next.
+ class Person(Form):
+ first_name = CharField(required=False)
+ last_name = CharField(required=False)
+
+ def __init__(self, names_required=False, *args, **kwargs):
+ super(Person, self).__init__(*args, **kwargs)
+
+ if names_required:
+ self.fields['first_name'].required = True
+ self.fields['first_name'].widget.attrs['class'] = 'required'
+ self.fields['last_name'].required = True
+ self.fields['last_name'].widget.attrs['class'] = 'required'
+
+ f = Person(names_required=False)
+ self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
+ self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
+ f = Person(names_required=True)
+ self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (True, True))
+ self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({'class': 'required'}, {'class': 'required'}))
+ f = Person(names_required=False)
+ self.assertEqual(f['first_name'].field.required, f['last_name'].field.required, (False, False))
+ self.assertEqual(f['first_name'].field.widget.attrs, f['last_name'].field.widget.attrs, ({}, {}))
+
+ class Person(Form):
+ first_name = CharField(max_length=30)
+ last_name = CharField(max_length=30)
+
+ def __init__(self, name_max_length=None, *args, **kwargs):
+ super(Person, self).__init__(*args, **kwargs)
+
+ if name_max_length:
+ self.fields['first_name'].max_length = name_max_length
+ self.fields['last_name'].max_length = name_max_length
+
+ f = Person(name_max_length=None)
+ self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
+ f = Person(name_max_length=20)
+ self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (20, 20))
+ f = Person(name_max_length=None)
+ self.assertEqual(f['first_name'].field.max_length, f['last_name'].field.max_length, (30, 30))
+
+ def test_hidden_widget(self):
+ # HiddenInput widgets are displayed differently in the as_table(), as_ul())
+ # and as_p() output of a Form -- their verbose names are not displayed, and a
+ # separate row is not displayed. They're displayed in the last row of the
+ # form, directly after that row's form element.
+ class Person(Form):
+ first_name = CharField()
+ last_name = CharField()
+ hidden_text = CharField(widget=HiddenInput)
+ birthday = DateField()
+
+ p = Person(auto_id=False)
+ self.assertEqual(p.as_table(), """
First name:
+
Last name:
+
Birthday:
""")
+ self.assertEqual(p.as_ul(), """
First name:
+
Last name:
+
Birthday:
""")
+ self.assertEqual(p.as_p(), """
First name:
+
Last name:
+
Birthday:
""")
+
+ # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
+ p = Person(auto_id='id_%s')
+ self.assertEqual(p.as_table(), """
First name:
+
Last name:
+
Birthday:
""")
+ self.assertEqual(p.as_ul(), """
First name:
+
Last name:
+
Birthday:
""")
+ self.assertEqual(p.as_p(), """
First name:
+
Last name:
+
Birthday:
""")
+
+ # If a field with a HiddenInput has errors, the as_table() and as_ul() output
+ # will include the error message(s) with the text "(Hidden field [fieldname]) "
+ # prepended. This message is displayed at the top of the output, regardless of
+ # its field's order in the form.
+ p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False)
+ self.assertEqual(p.as_table(), """
(Hidden field hidden_text) This field is required.
+
First name:
+
Last name:
+
Birthday:
""")
+ self.assertEqual(p.as_ul(), """
(Hidden field hidden_text) This field is required.
+
First name:
+
Last name:
+
Birthday:
""")
+ self.assertEqual(p.as_p(), """
(Hidden field hidden_text) This field is required.
+
First name:
+
Last name:
+
Birthday:
""")
+
+ # A corner case: It's possible for a form to have only HiddenInputs.
+ class TestForm(Form):
+ foo = CharField(widget=HiddenInput)
+ bar = CharField(widget=HiddenInput)
+
+ p = TestForm(auto_id=False)
+ self.assertEqual(p.as_table(), '')
+ self.assertEqual(p.as_ul(), '')
+ self.assertEqual(p.as_p(), '')
+
+ def test_field_order(self):
+ # A Form's fields are displayed in the same order in which they were defined.
+ class TestForm(Form):
+ field1 = CharField()
+ field2 = CharField()
+ field3 = CharField()
+ field4 = CharField()
+ field5 = CharField()
+ field6 = CharField()
+ field7 = CharField()
+ field8 = CharField()
+ field9 = CharField()
+ field10 = CharField()
+ field11 = CharField()
+ field12 = CharField()
+ field13 = CharField()
+ field14 = CharField()
+
+ p = TestForm(auto_id=False)
+ self.assertEqual(p.as_table(), """
Field1:
+
Field2:
+
Field3:
+
Field4:
+
Field5:
+
Field6:
+
Field7:
+
Field8:
+
Field9:
+
Field10:
+
Field11:
+
Field12:
+
Field13:
+
Field14:
""")
+
+ def test_form_html_attributes(self):
+ # Some Field classes have an effect on the HTML attributes of their associated
+ # Widget. If you set max_length in a CharField and its associated widget is
+ # either a TextInput or PasswordInput, then the widget's rendered HTML will
+ # include the "maxlength" attribute.
+ class UserRegistration(Form):
+ username = CharField(max_length=10) # uses TextInput by default
+ password = CharField(max_length=10, widget=PasswordInput)
+ realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test
+ address = CharField() # no max_length defined here
+
+ p = UserRegistration(auto_id=False)
+ self.assertEqual(p.as_ul(), """
Username:
+
Password:
+
Realname:
+
Address:
""")
+
+ # If you specify a custom "attrs" that includes the "maxlength" attribute,
+ # the Field's max_length attribute will override whatever "maxlength" you specify
+ # in "attrs".
+ class UserRegistration(Form):
+ username = CharField(max_length=10, widget=TextInput(attrs={'maxlength': 20}))
+ password = CharField(max_length=10, widget=PasswordInput)
+
+ p = UserRegistration(auto_id=False)
+ self.assertEqual(p.as_ul(), """
Username:
+
Password:
""")
+
+ def test_specifying_labels(self):
+ # You can specify the label for a field by using the 'label' argument to a Field
+ # class. If you don't specify 'label', Django will use the field name with
+ # underscores converted to spaces, and the initial letter capitalized.
+ class UserRegistration(Form):
+ username = CharField(max_length=10, label='Your username')
+ password1 = CharField(widget=PasswordInput)
+ password2 = CharField(widget=PasswordInput, label='Password (again)')
+
+ p = UserRegistration(auto_id=False)
+ self.assertEqual(p.as_ul(), """
Your username:
+
Password1:
+
Password (again):
""")
+
+ # Labels for as_* methods will only end in a colon if they don't end in other
+ # punctuation already.
+ class Questions(Form):
+ q1 = CharField(label='The first question')
+ q2 = CharField(label='What is your name?')
+ q3 = CharField(label='The answer to life is:')
+ q4 = CharField(label='Answer this question!')
+ q5 = CharField(label='The last question. Period.')
+
+ self.assertEqual(Questions(auto_id=False).as_p(), """
The first question:
+
What is your name?
+
The answer to life is:
+
Answer this question!
+
The last question. Period.
""")
+ self.assertEqual(Questions().as_p(), """
The first question:
+
What is your name?
+
The answer to life is:
+
Answer this question!
+
The last question. Period.
""")
+
+ # A label can be a Unicode object or a bytestring with special characters.
+ class UserRegistration(Form):
+ username = CharField(max_length=10, label='ŠĐĆŽćžšđ')
+ password = CharField(widget=PasswordInput, label=u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111')
+
+ p = UserRegistration(auto_id=False)
+ self.assertEqual(p.as_ul(), u'
\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111:
\n
\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111:
')
+
+ # If a label is set to the empty string for a field, that field won't get a label.
+ class UserRegistration(Form):
+ username = CharField(max_length=10, label='')
+ password = CharField(widget=PasswordInput)
+
+ p = UserRegistration(auto_id=False)
+ self.assertEqual(p.as_ul(), """
+
Password:
""")
+ p = UserRegistration(auto_id='id_%s')
+ self.assertEqual(p.as_ul(), """
+
Password:
""")
+
+ # If label is None, Django will auto-create the label from the field name. This
+ # is default behavior.
+ class UserRegistration(Form):
+ username = CharField(max_length=10, label=None)
+ password = CharField(widget=PasswordInput)
+
+ p = UserRegistration(auto_id=False)
+ self.assertEqual(p.as_ul(), """
Username:
+
Password:
""")
+ p = UserRegistration(auto_id='id_%s')
+ self.assertEqual(p.as_ul(), """
Username:
+
Password:
""")
+
+ def test_label_suffix(self):
+ # You can specify the 'label_suffix' argument to a Form class to modify the
+ # punctuation symbol used at the end of a label. By default, the colon (:) is
+ # used, and is only appended to the label if the label doesn't already end with a
+ # punctuation symbol: ., !, ? or :. If you specify a different suffix, it will
+ # be appended regardless of the last character of the label.
+ class FavoriteForm(Form):
+ color = CharField(label='Favorite color?')
+ animal = CharField(label='Favorite animal')
+
+ f = FavoriteForm(auto_id=False)
+ self.assertEqual(f.as_ul(), """
Favorite color?
+
Favorite animal:
""")
+ f = FavoriteForm(auto_id=False, label_suffix='?')
+ self.assertEqual(f.as_ul(), """
Favorite color?
+
Favorite animal?
""")
+ f = FavoriteForm(auto_id=False, label_suffix='')
+ self.assertEqual(f.as_ul(), """
Favorite color?
+
Favorite animal
""")
+ f = FavoriteForm(auto_id=False, label_suffix=u'\u2192')
+ self.assertEqual(f.as_ul(), u'
Favorite color?
\n
Favorite animal\u2192
')
+
+ def test_initial_data(self):
+ # You can specify initial data for a field by using the 'initial' argument to a
+ # Field class. This initial data is displayed when a Form is rendered with *no*
+ # data. It is not displayed when a Form is rendered with any data (including an
+ # empty dictionary). Also, the initial value is *not* used if data for a
+ # particular required field isn't provided.
+ class UserRegistration(Form):
+ username = CharField(max_length=10, initial='django')
+ password = CharField(widget=PasswordInput)
+
+ # Here, we're not submitting any data, so the initial value will be displayed.)
+ p = UserRegistration(auto_id=False)
+ self.assertEqual(p.as_ul(), """
Username:
+
Password:
""")
+
+ # Here, we're submitting data, so the initial value will *not* be displayed.
+ p = UserRegistration({}, auto_id=False)
+ self.assertEqual(p.as_ul(), """
This field is required.
Username:
+
This field is required.
Password:
""")
+ p = UserRegistration({'username': u''}, auto_id=False)
+ self.assertEqual(p.as_ul(), """
This field is required.
Username:
+
This field is required.
Password:
""")
+ p = UserRegistration({'username': u'foo'}, auto_id=False)
+ self.assertEqual(p.as_ul(), """
Username:
+
This field is required.
Password:
""")
+
+ # An 'initial' value is *not* used as a fallback if data is not provided. In this
+ # example, we don't provide a value for 'username', and the form raises a
+ # validation error rather than using the initial value for 'username'.
+ p = UserRegistration({'password': 'secret'})
+ self.assertEqual(p.errors['username'], [u'This field is required.'])
+ self.assertFalse(p.is_valid())
+
+ def test_dynamic_initial_data(self):
+ # The previous technique dealt with "hard-coded" initial data, but it's also
+ # possible to specify initial data after you've already created the Form class
+ # (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This
+ # should be a dictionary containing initial values for one or more fields in the
+ # form, keyed by field name.
+ class UserRegistration(Form):
+ username = CharField(max_length=10)
+ password = CharField(widget=PasswordInput)
+
+ # Here, we're not submitting any data, so the initial value will be displayed.)
+ p = UserRegistration(initial={'username': 'django'}, auto_id=False)
+ self.assertEqual(p.as_ul(), """
Username:
+
Password:
""")
+ p = UserRegistration(initial={'username': 'stephane'}, auto_id=False)
+ self.assertEqual(p.as_ul(), """
Username:
+
Password:
""")
+
+ # The 'initial' parameter is meaningless if you pass data.
+ p = UserRegistration({}, initial={'username': 'django'}, auto_id=False)
+ self.assertEqual(p.as_ul(), """
""")
+
+ # A dynamic 'initial' value is *not* used as a fallback if data is not provided.
+ # In this example, we don't provide a value for 'username', and the form raises a
+ # validation error rather than using the initial value for 'username'.
+ p = UserRegistration({'password': 'secret'}, initial={'username': 'django'})
+ self.assertEqual(p.errors['username'], [u'This field is required.'])
+ self.assertFalse(p.is_valid())
+
+ # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
+ # then the latter will get precedence.
+ class UserRegistration(Form):
+ username = CharField(max_length=10, initial='django')
+ password = CharField(widget=PasswordInput)
+
+ p = UserRegistration(initial={'username': 'babik'}, auto_id=False)
+ self.assertEqual(p.as_ul(), """
Username:
+
Password:
""")
+
+ def test_callable_initial_data(self):
+ # The previous technique dealt with raw values as initial data, but it's also
+ # possible to specify callable data.
+ class UserRegistration(Form):
+ username = CharField(max_length=10)
+ password = CharField(widget=PasswordInput)
+ options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')])
+
+ # We need to define functions that get called later.)
+ def initial_django():
+ return 'django'
+
+ def initial_stephane():
+ return 'stephane'
+
+ def initial_options():
+ return ['f','b']
+
+ def initial_other_options():
+ return ['b','w']
+
+ # Here, we're not submitting any data, so the initial value will be displayed.)
+ p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False)
+ self.assertEqual(p.as_ul(), """
Username:
+
Password:
+
Options:
""")
+
+ # The 'initial' parameter is meaningless if you pass data.
+ p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False)
+ self.assertEqual(p.as_ul(), """
""")
+
+ # A callable 'initial' value is *not* used as a fallback if data is not provided.
+ # In this example, we don't provide a value for 'username', and the form raises a
+ # validation error rather than using the initial value for 'username'.
+ p = UserRegistration({'password': 'secret'}, initial={'username': initial_django, 'options': initial_options})
+ self.assertEqual(p.errors['username'], [u'This field is required.'])
+ self.assertFalse(p.is_valid())
+
+ # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
+ # then the latter will get precedence.
+ class UserRegistration(Form):
+ username = CharField(max_length=10, initial=initial_django)
+ password = CharField(widget=PasswordInput)
+ options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')], initial=initial_other_options)
+
+ p = UserRegistration(auto_id=False)
+ self.assertEqual(p.as_ul(), """
""")
+
+ def test_help_text(self):
+ # You can specify descriptive text for a field by using the 'help_text' argument)
+ class UserRegistration(Form):
+ username = CharField(max_length=10, help_text='e.g., user@example.com')
+ password = CharField(widget=PasswordInput, help_text='Choose wisely.')
+
+ p = UserRegistration(auto_id=False)
+ self.assertEqual(p.as_ul(), """
Username: e.g., user@example.com
+
Password: Choose wisely.
""")
+ self.assertEqual(p.as_p(), """
Username: e.g., user@example.com
+
Password: Choose wisely.
""")
+ self.assertEqual(p.as_table(), """
Username:
e.g., user@example.com
+
Password:
Choose wisely.
""")
+
+ # The help text is displayed whether or not data is provided for the form.
+ p = UserRegistration({'username': u'foo'}, auto_id=False)
+ self.assertEqual(p.as_ul(), """
Username: e.g., user@example.com
+
This field is required.
Password: Choose wisely.
""")
+
+ # help_text is not displayed for hidden fields. It can be used for documentation
+ # purposes, though.
+ class UserRegistration(Form):
+ username = CharField(max_length=10, help_text='e.g., user@example.com')
+ password = CharField(widget=PasswordInput)
+ next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination')
+
+ p = UserRegistration(auto_id=False)
+ self.assertEqual(p.as_ul(), """
Username: e.g., user@example.com
+
Password:
""")
+
+ # Help text can include arbitrary Unicode characters.
+ class UserRegistration(Form):
+ username = CharField(max_length=10, help_text='ŠĐĆŽćžšđ')
+
+ p = UserRegistration(auto_id=False)
+ self.assertEqual(p.as_ul(), u'
')
+
+ def test_subclassing_forms(self):
+ # You can subclass a Form to add fields. The resulting form subclass will have
+ # all of the fields of the parent Form, plus whichever fields you define in the
+ # subclass.
+ class Person(Form):
+ first_name = CharField()
+ last_name = CharField()
+ birthday = DateField()
+
+ class Musician(Person):
+ instrument = CharField()
+
+ p = Person(auto_id=False)
+ self.assertEqual(p.as_ul(), """
First name:
+
Last name:
+
Birthday:
""")
+ m = Musician(auto_id=False)
+ self.assertEqual(m.as_ul(), """
First name:
+
Last name:
+
Birthday:
+
Instrument:
""")
+
+ # Yes, you can subclass multiple forms. The fields are added in the order in
+ # which the parent classes are listed.
+ class Person(Form):
+ first_name = CharField()
+ last_name = CharField()
+ birthday = DateField()
+
+ class Instrument(Form):
+ instrument = CharField()
+
+ class Beatle(Person, Instrument):
+ haircut_type = CharField()
+
+ b = Beatle(auto_id=False)
+ self.assertEqual(b.as_ul(), """
First name:
+
Last name:
+
Birthday:
+
Instrument:
+
Haircut type:
""")
+
+ def test_forms_with_prefixes(self):
+ # Sometimes it's necessary to have multiple forms display on the same HTML page,
+ # or multiple copies of the same form. We can accomplish this with form prefixes.
+ # Pass the keyword argument 'prefix' to the Form constructor to use this feature.
+ # This value will be prepended to each HTML form field name. One way to think
+ # about this is "namespaces for HTML forms". Notice that in the data argument,
+ # each field's key has the prefix, in this case 'person1', prepended to the
+ # actual field name.
+ class Person(Form):
+ first_name = CharField()
+ last_name = CharField()
+ birthday = DateField()
+
+ data = {
+ 'person1-first_name': u'John',
+ 'person1-last_name': u'Lennon',
+ 'person1-birthday': u'1940-10-9'
+ }
+ p = Person(data, prefix='person1')
+ self.assertEqual(p.as_ul(), """
First name:
+
Last name:
+
Birthday:
""")
+ self.assertEqual(str(p['first_name']), '')
+ self.assertEqual(str(p['last_name']), '')
+ self.assertEqual(str(p['birthday']), '')
+ self.assertEqual(p.errors, {})
+ self.assertTrue(p.is_valid())
+ self.assertEqual(p.cleaned_data['first_name'], u'John')
+ self.assertEqual(p.cleaned_data['last_name'], u'Lennon')
+ self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
+
+ # Let's try submitting some bad data to make sure form.errors and field.errors
+ # work as expected.
+ data = {
+ 'person1-first_name': u'',
+ 'person1-last_name': u'',
+ 'person1-birthday': u''
+ }
+ p = Person(data, prefix='person1')
+ self.assertEqual(p.errors['first_name'], [u'This field is required.'])
+ self.assertEqual(p.errors['last_name'], [u'This field is required.'])
+ self.assertEqual(p.errors['birthday'], [u'This field is required.'])
+ self.assertEqual(p['first_name'].errors, [u'This field is required.'])
+ try:
+ p['person1-first_name'].errors
+ self.fail('Attempts to access non-existent fields should fail.')
+ except KeyError:
+ pass
+
+ # In this example, the data doesn't have a prefix, but the form requires it, so
+ # the form doesn't "see" the fields.
+ data = {
+ 'first_name': u'John',
+ 'last_name': u'Lennon',
+ 'birthday': u'1940-10-9'
+ }
+ p = Person(data, prefix='person1')
+ self.assertEqual(p.errors['first_name'], [u'This field is required.'])
+ self.assertEqual(p.errors['last_name'], [u'This field is required.'])
+ self.assertEqual(p.errors['birthday'], [u'This field is required.'])
+
+ # With prefixes, a single data dictionary can hold data for multiple instances
+ # of the same form.
+ data = {
+ 'person1-first_name': u'John',
+ 'person1-last_name': u'Lennon',
+ 'person1-birthday': u'1940-10-9',
+ 'person2-first_name': u'Jim',
+ 'person2-last_name': u'Morrison',
+ 'person2-birthday': u'1943-12-8'
+ }
+ p1 = Person(data, prefix='person1')
+ self.assertTrue(p1.is_valid())
+ self.assertEqual(p1.cleaned_data['first_name'], u'John')
+ self.assertEqual(p1.cleaned_data['last_name'], u'Lennon')
+ self.assertEqual(p1.cleaned_data['birthday'], datetime.date(1940, 10, 9))
+ p2 = Person(data, prefix='person2')
+ self.assertTrue(p2.is_valid())
+ self.assertEqual(p2.cleaned_data['first_name'], u'Jim')
+ self.assertEqual(p2.cleaned_data['last_name'], u'Morrison')
+ self.assertEqual(p2.cleaned_data['birthday'], datetime.date(1943, 12, 8))
+
+ # By default, forms append a hyphen between the prefix and the field name, but a
+ # form can alter that behavior by implementing the add_prefix() method. This
+ # method takes a field name and returns the prefixed field, according to
+ # self.prefix.
+ class Person(Form):
+ first_name = CharField()
+ last_name = CharField()
+ birthday = DateField()
+
+ def add_prefix(self, field_name):
+ return self.prefix and '%s-prefix-%s' % (self.prefix, field_name) or field_name
+
+ p = Person(prefix='foo')
+ self.assertEqual(p.as_ul(), """
First name:
+
Last name:
+
Birthday:
""")
+ data = {
+ 'foo-prefix-first_name': u'John',
+ 'foo-prefix-last_name': u'Lennon',
+ 'foo-prefix-birthday': u'1940-10-9'
+ }
+ p = Person(data, prefix='foo')
+ self.assertTrue(p.is_valid())
+ self.assertEqual(p.cleaned_data['first_name'], u'John')
+ self.assertEqual(p.cleaned_data['last_name'], u'Lennon')
+ self.assertEqual(p.cleaned_data['birthday'], datetime.date(1940, 10, 9))
+
+ def test_forms_with_null_boolean(self):
+ # NullBooleanField is a bit of a special case because its presentation (widget)
+ # is different than its data. This is handled transparently, though.
+ class Person(Form):
+ name = CharField()
+ is_cool = NullBooleanField()
+
+ p = Person({'name': u'Joe'}, auto_id=False)
+ self.assertEqual(str(p['is_cool']), """""")
+ p = Person({'name': u'Joe', 'is_cool': u'1'}, auto_id=False)
+ self.assertEqual(str(p['is_cool']), """""")
+ p = Person({'name': u'Joe', 'is_cool': u'2'}, auto_id=False)
+ self.assertEqual(str(p['is_cool']), """""")
+ p = Person({'name': u'Joe', 'is_cool': u'3'}, auto_id=False)
+ self.assertEqual(str(p['is_cool']), """""")
+ p = Person({'name': u'Joe', 'is_cool': True}, auto_id=False)
+ self.assertEqual(str(p['is_cool']), """""")
+ p = Person({'name': u'Joe', 'is_cool': False}, auto_id=False)
+ self.assertEqual(str(p['is_cool']), """""")
+
+ def test_forms_with_file_fields(self):
+ # FileFields are a special case because they take their data from the request.FILES,
+ # not request.POST.
+ class FileForm(Form):
+ file1 = FileField()
+
+ f = FileForm(auto_id=False)
+ self.assertEqual(f.as_table(), '
')
+ self.assertTrue(f.is_valid())
+
+ f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')}, auto_id=False)
+ self.assertEqual(f.as_table(), '
File1:
')
+
+ def test_basic_processing_in_view(self):
+ class UserRegistration(Form):
+ username = CharField(max_length=10)
+ password1 = CharField(widget=PasswordInput)
+ password2 = CharField(widget=PasswordInput)
+
+ def clean(self):
+ if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
+ raise ValidationError(u'Please make sure your passwords match.')
+
+ return self.cleaned_data
+
+ def my_function(method, post_data):
+ if method == 'POST':
+ form = UserRegistration(post_data, auto_id=False)
+ else:
+ form = UserRegistration(auto_id=False)
+
+ if form.is_valid():
+ return 'VALID: %r' % form.cleaned_data
+
+ t = Template('')
+ return t.render(Context({'form': form}))
+
+ # Case 1: GET (an empty form, with no errors).)
+ self.assertEqual(my_function('GET', {}), """""")
+ # Case 2: POST with erroneous data (a redisplayed form, with errors).)
+ self.assertEqual(my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}), """""")
+ # Case 3: POST with valid data (the success message).)
+ self.assertEqual(my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}), "VALID: {'username': u'adrian', 'password1': u'secret', 'password2': u'secret'}")
+
+ def test_templates_with_forms(self):
+ class UserRegistration(Form):
+ username = CharField(max_length=10, help_text="Good luck picking a username that doesn't already exist.")
+ password1 = CharField(widget=PasswordInput)
+ password2 = CharField(widget=PasswordInput)
+
+ def clean(self):
+ if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
+ raise ValidationError(u'Please make sure your passwords match.')
+
+ return self.cleaned_data
+
+ # You have full flexibility in displaying form fields in a template. Just pass a
+ # Form instance to the template, and use "dot" access to refer to individual
+ # fields. Note, however, that this flexibility comes with the responsibility of
+ # displaying all the errors, including any that might not be associated with a
+ # particular field.
+ t = Template('''''')
+ self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """""")
+ self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})), """""")
+
+ # 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('''''')
+ self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """""")
+
+ # User form.[field].label_tag to output a field's label with a 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('''''')
+ self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """""")
+ self.assertEqual(t.render(Context({'form': UserRegistration(auto_id='id_%s')})), """""")
+
+ # 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('''''')
+ self.assertEqual(t.render(Context({'form': UserRegistration(auto_id=False)})), """""")
+ self.assertEqual(Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)})), u'')
+
+ # The label_tag() method takes an optional attrs argument: a dictionary of HTML
+ # attributes to add to the tag.
+ f = UserRegistration(auto_id='id_%s')
+ form_output = []
+
+ for bf in f:
+ form_output.append(bf.label_tag(attrs={'class': 'pretty'}))
+
+ self.assertEqual(form_output, [
+ 'Username',
+ 'Password1',
+ 'Password2',
+ ])
+
+ # 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
(or an empty string, if
+ # the list of errors is empty). You can also use it in {% if %} statements.
+ t = Template('''
''')
+ self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """""")
+ t = Template('''''')
+ self.assertEqual(t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)})), """""")
+
+ def test_empty_permitted(self):
+ # Sometimes (pretty much in formsets) we want to allow a form to pass validation
+ # if it is completely empty. We can accomplish this by using the empty_permitted
+ # agrument to a form constructor.
+ class SongForm(Form):
+ artist = CharField()
+ name = CharField()
+
+ # First let's show what happens id empty_permitted=False (the default):
+ data = {'artist': '', 'song': ''}
+ form = SongForm(data, empty_permitted=False)
+ self.assertFalse(form.is_valid())
+ self.assertEqual(form.errors, {'name': [u'This field is required.'], 'artist': [u'This field is required.']})
+ try:
+ form.cleaned_data
+ self.fail('Attempts to access cleaned_data when validation fails should fail.')
+ except AttributeError:
+ pass
+
+ # Now let's show what happens when empty_permitted=True and the form is empty.
+ form = SongForm(data, empty_permitted=True)
+ self.assertTrue(form.is_valid())
+ self.assertEqual(form.errors, {})
+ self.assertEqual(form.cleaned_data, {})
+
+ # But if we fill in data for one of the fields, the form is no longer empty and
+ # the whole thing must pass validation.
+ data = {'artist': 'The Doors', 'song': ''}
+ form = SongForm(data, empty_permitted=False)
+ self.assertFalse(form.is_valid())
+ self.assertEqual(form.errors, {'name': [u'This field is required.']})
+ try:
+ form.cleaned_data
+ self.fail('Attempts to access cleaned_data when validation fails should fail.')
+ except AttributeError:
+ pass
+
+ # If a field is not given in the data then None is returned for its data. Lets
+ # make sure that when checking for empty_permitted that None is treated
+ # accordingly.
+ data = {'artist': None, 'song': ''}
+ form = SongForm(data, empty_permitted=True)
+ self.assertTrue(form.is_valid())
+
+ # However, we *really* need to be sure we are checking for None as any data in
+ # initial that returns False on a boolean call needs to be treated literally.
+ class PriceForm(Form):
+ amount = FloatField()
+ qty = IntegerField()
+
+ data = {'amount': '0.0', 'qty': ''}
+ form = PriceForm(data, initial={'amount': 0.0}, empty_permitted=True)
+ self.assertTrue(form.is_valid())
+
+ def test_extracting_hidden_and_visible(self):
+ class SongForm(Form):
+ token = CharField(widget=HiddenInput)
+ artist = CharField()
+ name = CharField()
+
+ form = SongForm()
+ self.assertEqual([f.name for f in form.hidden_fields()], ['token'])
+ self.assertEqual([f.name for f in form.visible_fields()], ['artist', 'name'])
+
+ def test_hidden_initial_gets_id(self):
+ class MyForm(Form):
+ field1 = CharField(max_length=50, show_hidden_initial=True)
+
+ self.assertEqual(MyForm().as_table(), '
""")
+
+ def test_label_split_datetime_not_displayed(self):
+ class EventForm(Form):
+ happened_at = SplitDateTimeField(widget=widgets.SplitHiddenDateTimeWidget)
+
+ form = EventForm()
+ self.assertEqual(form.as_ul(), u'')
diff --git a/tests/regressiontests/forms/tests/formsets.py b/tests/regressiontests/forms/tests/formsets.py
new file mode 100644
index 0000000000..bf7124fe59
--- /dev/null
+++ b/tests/regressiontests/forms/tests/formsets.py
@@ -0,0 +1,797 @@
+# -*- coding: utf-8 -*-
+from django.forms import Form, CharField, IntegerField, ValidationError
+from django.forms.formsets import formset_factory, BaseFormSet
+from django.utils.unittest import TestCase
+
+
+class Choice(Form):
+ choice = CharField()
+ votes = IntegerField()
+
+
+# FormSet allows us to use multiple instance of the same form on 1 page. For now,
+# the best way to create a FormSet is by using the formset_factory function.
+ChoiceFormSet = formset_factory(Choice)
+
+
+class FavoriteDrinkForm(Form):
+ name = CharField()
+
+
+class BaseFavoriteDrinksFormSet(BaseFormSet):
+ def clean(self):
+ seen_drinks = []
+
+ for drink in self.cleaned_data:
+ if drink['name'] in seen_drinks:
+ raise ValidationError('You may only specify a drink once.')
+
+ seen_drinks.append(drink['name'])
+
+
+# Let's define a FormSet that takes a list of favorite drinks, but raises an
+# error if there are any duplicates. Used in ``test_clean_hook``,
+# ``test_regression_6926`` & ``test_regression_12878``.
+FavoriteDrinksFormSet = formset_factory(FavoriteDrinkForm,
+ formset=BaseFavoriteDrinksFormSet, extra=3)
+
+
+class FormsFormsetTestCase(TestCase):
+ def test_basic_formset(self):
+ # A FormSet constructor takes the same arguments as Form. Let's create a FormSet
+ # for adding data. By default, it displays 1 blank form. It can display more,
+ # but we'll look at how to do so later.
+ formset = ChoiceFormSet(auto_id=False, prefix='choices')
+ self.assertEqual(str(formset), """
+
Choice:
+
Votes:
""")
+
+ # On thing to note is that there needs to be a special value in the data. This
+ # value tells the FormSet how many forms were displayed so it can tell how
+ # many forms it needs to clean and validate. You could use javascript to create
+ # new forms on the client side, but they won't get validated unless you increment
+ # the TOTAL_FORMS field appropriately.
+
+ data = {
+ 'choices-TOTAL_FORMS': '1', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': 'Calexico',
+ 'choices-0-votes': '100',
+ }
+ # We treat FormSet pretty much like we would treat a normal Form. FormSet has an
+ # is_valid method, and a cleaned_data or errors attribute depending on whether all
+ # the forms passed validation. However, unlike a Form instance, cleaned_data and
+ # errors will be a list of dicts rather than just a single dict.
+
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertTrue(formset.is_valid())
+ self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': u'Calexico'}])
+
+ # If a FormSet was not passed any data, its is_valid method should return False.
+ formset = ChoiceFormSet()
+ self.assertFalse(formset.is_valid())
+
+ def test_formset_validation(self):
+ # FormSet instances can also have an error attribute if validation failed for
+ # any of the forms.
+
+ data = {
+ 'choices-TOTAL_FORMS': '1', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': 'Calexico',
+ 'choices-0-votes': '',
+ }
+
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertFalse(formset.is_valid())
+ self.assertEqual(formset.errors, [{'votes': [u'This field is required.']}])
+
+ def test_formset_initial_data(self):
+ # We can also prefill a FormSet with existing data by providing an ``initial``
+ # argument to the constructor. ``initial`` should be a list of dicts. By default,
+ # an extra blank form is included.
+
+ initial = [{'choice': u'Calexico', 'votes': 100}]
+ formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
+ form_output = []
+
+ for form in formset.forms:
+ form_output.append(form.as_ul())
+
+ self.assertEqual('\n'.join(form_output), """
Choice:
+
Votes:
+
Choice:
+
Votes:
""")
+
+ # Let's simulate what would happen if we submitted this form.
+
+ data = {
+ 'choices-TOTAL_FORMS': '2', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '1', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': 'Calexico',
+ 'choices-0-votes': '100',
+ 'choices-1-choice': '',
+ 'choices-1-votes': '',
+ }
+
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertTrue(formset.is_valid())
+ self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': u'Calexico'}, {}])
+
+ def test_second_form_partially_filled(self):
+ # But the second form was blank! Shouldn't we get some errors? No. If we display
+ # a form as blank, it's ok for it to be submitted as blank. If we fill out even
+ # one of the fields of a blank form though, it will be validated. We may want to
+ # required that at least x number of forms are completed, but we'll show how to
+ # handle that later.
+
+ data = {
+ 'choices-TOTAL_FORMS': '2', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '1', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': 'Calexico',
+ 'choices-0-votes': '100',
+ 'choices-1-choice': 'The Decemberists',
+ 'choices-1-votes': '', # missing value
+ }
+
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertFalse(formset.is_valid())
+ self.assertEqual(formset.errors, [{}, {'votes': [u'This field is required.']}])
+
+ def test_delete_prefilled_data(self):
+ # If we delete data that was pre-filled, we should get an error. Simply removing
+ # data from form fields isn't the proper way to delete it. We'll see how to
+ # handle that case later.
+
+ data = {
+ 'choices-TOTAL_FORMS': '2', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '1', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': '', # deleted value
+ 'choices-0-votes': '', # deleted value
+ 'choices-1-choice': '',
+ 'choices-1-votes': '',
+ }
+
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertFalse(formset.is_valid())
+ self.assertEqual(formset.errors, [{'votes': [u'This field is required.'], 'choice': [u'This field is required.']}, {}])
+
+ def test_displaying_more_than_one_blank_form(self):
+ # Displaying more than 1 blank form ###########################################
+ # We can also display more than 1 empty form at a time. To do so, pass a
+ # extra argument to formset_factory.
+ ChoiceFormSet = formset_factory(Choice, extra=3)
+
+ formset = ChoiceFormSet(auto_id=False, prefix='choices')
+ form_output = []
+
+ for form in formset.forms:
+ form_output.append(form.as_ul())
+
+ self.assertEqual('\n'.join(form_output), """
Choice:
+
Votes:
+
Choice:
+
Votes:
+
Choice:
+
Votes:
""")
+
+ # Since we displayed every form as blank, we will also accept them back as blank.
+ # This may seem a little strange, but later we will show how to require a minimum
+ # number of forms to be completed.
+
+ data = {
+ 'choices-TOTAL_FORMS': '3', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': '',
+ 'choices-0-votes': '',
+ 'choices-1-choice': '',
+ 'choices-1-votes': '',
+ 'choices-2-choice': '',
+ 'choices-2-votes': '',
+ }
+
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertTrue(formset.is_valid())
+ self.assertEqual([form.cleaned_data for form in formset.forms], [{}, {}, {}])
+
+ def test_single_form_completed(self):
+ # We can just fill out one of the forms.
+
+ data = {
+ 'choices-TOTAL_FORMS': '3', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': 'Calexico',
+ 'choices-0-votes': '100',
+ 'choices-1-choice': '',
+ 'choices-1-votes': '',
+ 'choices-2-choice': '',
+ 'choices-2-votes': '',
+ }
+
+ ChoiceFormSet = formset_factory(Choice, extra=3)
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertTrue(formset.is_valid())
+ self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': u'Calexico'}, {}, {}])
+
+ def test_second_form_partially_filled_2(self):
+ # And once again, if we try to partially complete a form, validation will fail.
+
+ data = {
+ 'choices-TOTAL_FORMS': '3', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': 'Calexico',
+ 'choices-0-votes': '100',
+ 'choices-1-choice': 'The Decemberists',
+ 'choices-1-votes': '', # missing value
+ 'choices-2-choice': '',
+ 'choices-2-votes': '',
+ }
+
+ ChoiceFormSet = formset_factory(Choice, extra=3)
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertFalse(formset.is_valid())
+ self.assertEqual(formset.errors, [{}, {'votes': [u'This field is required.']}, {}])
+
+ def test_more_initial_data(self):
+ # The extra argument also works when the formset is pre-filled with initial
+ # data.
+
+ data = {
+ 'choices-TOTAL_FORMS': '3', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': 'Calexico',
+ 'choices-0-votes': '100',
+ 'choices-1-choice': '',
+ 'choices-1-votes': '', # missing value
+ 'choices-2-choice': '',
+ 'choices-2-votes': '',
+ }
+
+ initial = [{'choice': u'Calexico', 'votes': 100}]
+ ChoiceFormSet = formset_factory(Choice, extra=3)
+ formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
+ form_output = []
+
+ for form in formset.forms:
+ form_output.append(form.as_ul())
+
+ self.assertEqual('\n'.join(form_output), """
Choice:
+
Votes:
+
Choice:
+
Votes:
+
Choice:
+
Votes:
+
Choice:
+
Votes:
""")
+
+ # Make sure retrieving an empty form works, and it shows up in the form list
+
+ self.assertTrue(formset.empty_form.empty_permitted)
+ self.assertEqual(formset.empty_form.as_ul(), """
Choice:
+
Votes:
""")
+
+ def test_formset_with_deletion(self):
+ # FormSets with deletion ######################################################
+ # We can easily add deletion ability to a FormSet with an argument to
+ # formset_factory. This will add a boolean field to each form instance. When
+ # that boolean field is True, the form will be in formset.deleted_forms
+
+ ChoiceFormSet = formset_factory(Choice, can_delete=True)
+
+ initial = [{'choice': u'Calexico', 'votes': 100}, {'choice': u'Fergie', 'votes': 900}]
+ formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
+ form_output = []
+
+ for form in formset.forms:
+ form_output.append(form.as_ul())
+
+ self.assertEqual('\n'.join(form_output), """
Choice:
+
Votes:
+
Delete:
+
Choice:
+
Votes:
+
Delete:
+
Choice:
+
Votes:
+
Delete:
""")
+
+ # To delete something, we just need to set that form's special delete field to
+ # 'on'. Let's go ahead and delete Fergie.
+
+ data = {
+ 'choices-TOTAL_FORMS': '3', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '2', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': 'Calexico',
+ 'choices-0-votes': '100',
+ 'choices-0-DELETE': '',
+ 'choices-1-choice': 'Fergie',
+ 'choices-1-votes': '900',
+ 'choices-1-DELETE': 'on',
+ 'choices-2-choice': '',
+ 'choices-2-votes': '',
+ 'choices-2-DELETE': '',
+ }
+
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertTrue(formset.is_valid())
+ self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'DELETE': False, 'choice': u'Calexico'}, {'votes': 900, 'DELETE': True, 'choice': u'Fergie'}, {}])
+ self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'choice': u'Fergie'}])
+
+ # If we fill a form with something and then we check the can_delete checkbox for
+ # that form, that form's errors should not make the entire formset invalid since
+ # it's going to be deleted.
+
+ class CheckForm(Form):
+ field = IntegerField(min_value=100)
+
+ data = {
+ 'check-TOTAL_FORMS': '3', # the number of forms rendered
+ 'check-INITIAL_FORMS': '2', # the number of forms with initial data
+ 'check-MAX_NUM_FORMS': '0', # max number of forms
+ 'check-0-field': '200',
+ 'check-0-DELETE': '',
+ 'check-1-field': '50',
+ 'check-1-DELETE': 'on',
+ 'check-2-field': '',
+ 'check-2-DELETE': '',
+ }
+ CheckFormSet = formset_factory(CheckForm, can_delete=True)
+ formset = CheckFormSet(data, prefix='check')
+ self.assertTrue(formset.is_valid())
+
+ # If we remove the deletion flag now we will have our validation back.
+ data['check-1-DELETE'] = ''
+ formset = CheckFormSet(data, prefix='check')
+ self.assertFalse(formset.is_valid())
+
+ # Should be able to get deleted_forms from a valid formset even if a
+ # deleted form would have been invalid.
+
+ class Person(Form):
+ name = CharField()
+
+ PeopleForm = formset_factory(
+ form=Person,
+ can_delete=True)
+
+ p = PeopleForm(
+ {'form-0-name': u'', 'form-0-DELETE': u'on', # no name!
+ 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1,
+ 'form-MAX_NUM_FORMS': 1})
+
+ self.assertTrue(p.is_valid())
+ self.assertEqual(len(p.deleted_forms), 1)
+
+ def test_formsets_with_ordering(self):
+ # FormSets with ordering ######################################################
+ # We can also add ordering ability to a FormSet with an argument to
+ # formset_factory. This will add a integer field to each form instance. When
+ # form validation succeeds, [form.cleaned_data for form in formset.forms] will have the data in the correct
+ # order specified by the ordering fields. If a number is duplicated in the set
+ # of ordering fields, for instance form 0 and form 3 are both marked as 1, then
+ # the form index used as a secondary ordering criteria. In order to put
+ # something at the front of the list, you'd need to set it's order to 0.
+
+ ChoiceFormSet = formset_factory(Choice, can_order=True)
+
+ initial = [{'choice': u'Calexico', 'votes': 100}, {'choice': u'Fergie', 'votes': 900}]
+ formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
+ form_output = []
+
+ for form in formset.forms:
+ form_output.append(form.as_ul())
+
+ self.assertEqual('\n'.join(form_output), """
Choice:
+
Votes:
+
Order:
+
Choice:
+
Votes:
+
Order:
+
Choice:
+
Votes:
+
Order:
""")
+
+ data = {
+ 'choices-TOTAL_FORMS': '3', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '2', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': 'Calexico',
+ 'choices-0-votes': '100',
+ 'choices-0-ORDER': '1',
+ 'choices-1-choice': 'Fergie',
+ 'choices-1-votes': '900',
+ 'choices-1-ORDER': '2',
+ 'choices-2-choice': 'The Decemberists',
+ 'choices-2-votes': '500',
+ 'choices-2-ORDER': '0',
+ }
+
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertTrue(formset.is_valid())
+ form_output = []
+
+ for form in formset.ordered_forms:
+ form_output.append(form.cleaned_data)
+
+ self.assertEqual(form_output, [
+ {'votes': 500, 'ORDER': 0, 'choice': u'The Decemberists'},
+ {'votes': 100, 'ORDER': 1, 'choice': u'Calexico'},
+ {'votes': 900, 'ORDER': 2, 'choice': u'Fergie'},
+ ])
+
+ def test_empty_ordered_fields(self):
+ # Ordering fields are allowed to be left blank, and if they *are* left blank,
+ # they will be sorted below everything else.
+
+ data = {
+ 'choices-TOTAL_FORMS': '4', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '3', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': 'Calexico',
+ 'choices-0-votes': '100',
+ 'choices-0-ORDER': '1',
+ 'choices-1-choice': 'Fergie',
+ 'choices-1-votes': '900',
+ 'choices-1-ORDER': '2',
+ 'choices-2-choice': 'The Decemberists',
+ 'choices-2-votes': '500',
+ 'choices-2-ORDER': '',
+ 'choices-3-choice': 'Basia Bulat',
+ 'choices-3-votes': '50',
+ 'choices-3-ORDER': '',
+ }
+
+ ChoiceFormSet = formset_factory(Choice, can_order=True)
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertTrue(formset.is_valid())
+ form_output = []
+
+ for form in formset.ordered_forms:
+ form_output.append(form.cleaned_data)
+
+ self.assertEqual(form_output, [
+ {'votes': 100, 'ORDER': 1, 'choice': u'Calexico'},
+ {'votes': 900, 'ORDER': 2, 'choice': u'Fergie'},
+ {'votes': 500, 'ORDER': None, 'choice': u'The Decemberists'},
+ {'votes': 50, 'ORDER': None, 'choice': u'Basia Bulat'},
+ ])
+
+ def test_ordering_blank_fieldsets(self):
+ # Ordering should work with blank fieldsets.
+
+ data = {
+ 'choices-TOTAL_FORMS': '3', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ }
+
+ ChoiceFormSet = formset_factory(Choice, can_order=True)
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertTrue(formset.is_valid())
+ form_output = []
+
+ for form in formset.ordered_forms:
+ form_output.append(form.cleaned_data)
+
+ self.assertEqual(form_output, [])
+
+ def test_formset_with_ordering_and_deletion(self):
+ # FormSets with ordering + deletion ###########################################
+ # Let's try throwing ordering and deletion into the same form.
+
+ ChoiceFormSet = formset_factory(Choice, can_order=True, can_delete=True)
+
+ initial = [
+ {'choice': u'Calexico', 'votes': 100},
+ {'choice': u'Fergie', 'votes': 900},
+ {'choice': u'The Decemberists', 'votes': 500},
+ ]
+ formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
+ form_output = []
+
+ for form in formset.forms:
+ form_output.append(form.as_ul())
+
+ self.assertEqual('\n'.join(form_output), """
Choice:
+
Votes:
+
Order:
+
Delete:
+
Choice:
+
Votes:
+
Order:
+
Delete:
+
Choice:
+
Votes:
+
Order:
+
Delete:
+
Choice:
+
Votes:
+
Order:
+
Delete:
""")
+
+ # Let's delete Fergie, and put The Decemberists ahead of Calexico.
+
+ data = {
+ 'choices-TOTAL_FORMS': '4', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '3', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': 'Calexico',
+ 'choices-0-votes': '100',
+ 'choices-0-ORDER': '1',
+ 'choices-0-DELETE': '',
+ 'choices-1-choice': 'Fergie',
+ 'choices-1-votes': '900',
+ 'choices-1-ORDER': '2',
+ 'choices-1-DELETE': 'on',
+ 'choices-2-choice': 'The Decemberists',
+ 'choices-2-votes': '500',
+ 'choices-2-ORDER': '0',
+ 'choices-2-DELETE': '',
+ 'choices-3-choice': '',
+ 'choices-3-votes': '',
+ 'choices-3-ORDER': '',
+ 'choices-3-DELETE': '',
+ }
+
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertTrue(formset.is_valid())
+ form_output = []
+
+ for form in formset.ordered_forms:
+ form_output.append(form.cleaned_data)
+
+ self.assertEqual(form_output, [
+ {'votes': 500, 'DELETE': False, 'ORDER': 0, 'choice': u'The Decemberists'},
+ {'votes': 100, 'DELETE': False, 'ORDER': 1, 'choice': u'Calexico'},
+ ])
+ self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': u'Fergie'}])
+
+ def test_invalid_deleted_form_with_ordering(self):
+ # Should be able to get ordered forms from a valid formset even if a
+ # deleted form would have been invalid.
+
+ class Person(Form):
+ name = CharField()
+
+ PeopleForm = formset_factory(form=Person, can_delete=True, can_order=True)
+
+ p = PeopleForm({
+ 'form-0-name': u'',
+ 'form-0-DELETE': u'on', # no name!
+ 'form-TOTAL_FORMS': 1,
+ 'form-INITIAL_FORMS': 1,
+ 'form-MAX_NUM_FORMS': 1
+ })
+
+ self.assertTrue(p.is_valid())
+ self.assertEqual(p.ordered_forms, [])
+
+ def test_clean_hook(self):
+ # FormSet clean hook ##########################################################
+ # FormSets have a hook for doing extra validation that shouldn't be tied to any
+ # particular form. It follows the same pattern as the clean hook on Forms.
+
+ # We start out with a some duplicate data.
+
+ data = {
+ 'drinks-TOTAL_FORMS': '2', # the number of forms rendered
+ 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data
+ 'drinks-MAX_NUM_FORMS': '0', # max number of forms
+ 'drinks-0-name': 'Gin and Tonic',
+ 'drinks-1-name': 'Gin and Tonic',
+ }
+
+ formset = FavoriteDrinksFormSet(data, prefix='drinks')
+ self.assertFalse(formset.is_valid())
+
+ # Any errors raised by formset.clean() are available via the
+ # formset.non_form_errors() method.
+
+ for error in formset.non_form_errors():
+ self.assertEqual(str(error), 'You may only specify a drink once.')
+
+ # Make sure we didn't break the valid case.
+
+ data = {
+ 'drinks-TOTAL_FORMS': '2', # the number of forms rendered
+ 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data
+ 'drinks-MAX_NUM_FORMS': '0', # max number of forms
+ 'drinks-0-name': 'Gin and Tonic',
+ 'drinks-1-name': 'Bloody Mary',
+ }
+
+ formset = FavoriteDrinksFormSet(data, prefix='drinks')
+ self.assertTrue(formset.is_valid())
+ self.assertEqual(formset.non_form_errors(), [])
+
+ def test_limiting_max_forms(self):
+ # Limiting the maximum number of forms ########################################
+ # Base case for max_num.
+
+ # When not passed, max_num will take its default value of None, i.e. unlimited
+ # number of forms, only controlled by the value of the extra parameter.
+
+ LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3)
+ formset = LimitedFavoriteDrinkFormSet()
+ form_output = []
+
+ for form in formset.forms:
+ form_output.append(str(form))
+
+ self.assertEqual('\n'.join(form_output), """
Name:
+
Name:
+
Name:
""")
+
+ # If max_num is 0 then no form is rendered at all.
+ LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=0)
+ formset = LimitedFavoriteDrinkFormSet()
+ form_output = []
+
+ for form in formset.forms:
+ form_output.append(str(form))
+
+ self.assertEqual('\n'.join(form_output), "")
+
+ LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=5, max_num=2)
+ formset = LimitedFavoriteDrinkFormSet()
+ form_output = []
+
+ for form in formset.forms:
+ form_output.append(str(form))
+
+ self.assertEqual('\n'.join(form_output), """
Name:
+
Name:
""")
+
+ # Ensure that max_num has no effect when extra is less than max_num.
+
+ LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2)
+ formset = LimitedFavoriteDrinkFormSet()
+ form_output = []
+
+ for form in formset.forms:
+ form_output.append(str(form))
+
+ self.assertEqual('\n'.join(form_output), """
Name:
""")
+
+ def test_max_num_with_initial_data(self):
+ # max_num with initial data
+
+ # When not passed, max_num will take its default value of None, i.e. unlimited
+ # number of forms, only controlled by the values of the initial and extra
+ # parameters.
+
+ initial = [
+ {'name': 'Fernet and Coke'},
+ ]
+ LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1)
+ formset = LimitedFavoriteDrinkFormSet(initial=initial)
+ form_output = []
+
+ for form in formset.forms:
+ form_output.append(str(form))
+
+ self.assertEqual('\n'.join(form_output), """
Name:
+
Name:
""")
+
+ def test_max_num_zero(self):
+ # If max_num is 0 then no form is rendered at all, even if extra and initial
+ # are specified.
+
+ initial = [
+ {'name': 'Fernet and Coke'},
+ {'name': 'Bloody Mary'},
+ ]
+ LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=0)
+ formset = LimitedFavoriteDrinkFormSet(initial=initial)
+ form_output = []
+
+ for form in formset.forms:
+ form_output.append(str(form))
+
+ self.assertEqual('\n'.join(form_output), "")
+
+ def test_more_initial_than_max_num(self):
+ # More initial forms than max_num will result in only the first max_num of
+ # them to be displayed with no extra forms.
+
+ initial = [
+ {'name': 'Gin Tonic'},
+ {'name': 'Bloody Mary'},
+ {'name': 'Jack and Coke'},
+ ]
+ LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2)
+ formset = LimitedFavoriteDrinkFormSet(initial=initial)
+ form_output = []
+
+ for form in formset.forms:
+ form_output.append(str(form))
+
+ self.assertEqual('\n'.join(form_output), """
Name:
+
Name:
""")
+
+ # One form from initial and extra=3 with max_num=2 should result in the one
+ # initial form and one extra.
+ initial = [
+ {'name': 'Gin Tonic'},
+ ]
+ LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=2)
+ formset = LimitedFavoriteDrinkFormSet(initial=initial)
+ form_output = []
+
+ for form in formset.forms:
+ form_output.append(str(form))
+
+ self.assertEqual('\n'.join(form_output), """
Name:
+
Name:
""")
+
+ def test_regression_6926(self):
+ # Regression test for #6926 ##################################################
+ # Make sure the management form has the correct prefix.
+
+ formset = FavoriteDrinksFormSet()
+ self.assertEqual(formset.management_form.prefix, 'form')
+
+ formset = FavoriteDrinksFormSet(data={})
+ self.assertEqual(formset.management_form.prefix, 'form')
+
+ formset = FavoriteDrinksFormSet(initial={})
+ self.assertEqual(formset.management_form.prefix, 'form')
+
+ def test_regression_12878(self):
+ # Regression test for #12878 #################################################
+
+ data = {
+ 'drinks-TOTAL_FORMS': '2', # the number of forms rendered
+ 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data
+ 'drinks-MAX_NUM_FORMS': '0', # max number of forms
+ 'drinks-0-name': 'Gin and Tonic',
+ 'drinks-1-name': 'Gin and Tonic',
+ }
+
+ formset = FavoriteDrinksFormSet(data, prefix='drinks')
+ self.assertFalse(formset.is_valid())
+ self.assertEqual(formset.non_form_errors(), [u'You may only specify a drink once.'])
+
+
+data = {
+ 'choices-TOTAL_FORMS': '1', # the number of forms rendered
+ 'choices-INITIAL_FORMS': '0', # the number of forms with initial data
+ 'choices-MAX_NUM_FORMS': '0', # max number of forms
+ 'choices-0-choice': 'Calexico',
+ 'choices-0-votes': '100',
+}
+
+class Choice(Form):
+ choice = CharField()
+ votes = IntegerField()
+
+ChoiceFormSet = formset_factory(Choice)
+
+class FormsetAsFooTests(TestCase):
+ def test_as_table(self):
+ formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
+ self.assertEqual(formset.as_table(),"""
+
""")
diff --git a/tests/regressiontests/forms/tests/input_formats.py b/tests/regressiontests/forms/tests/input_formats.py
new file mode 100644
index 0000000000..e362620ddb
--- /dev/null
+++ b/tests/regressiontests/forms/tests/input_formats.py
@@ -0,0 +1,894 @@
+from datetime import time, date, datetime
+
+from django import forms
+from django.conf import settings
+from django.utils.translation import activate, deactivate
+from django.utils.unittest import TestCase
+
+
+class LocalizedTimeTests(TestCase):
+ def setUp(self):
+ self.old_TIME_INPUT_FORMATS = settings.TIME_INPUT_FORMATS
+ self.old_USE_L10N = settings.USE_L10N
+
+ settings.TIME_INPUT_FORMATS = ["%I:%M:%S %p", "%I:%M %p"]
+ settings.USE_L10N = True
+
+ activate('de')
+
+ def tearDown(self):
+ settings.TIME_INPUT_FORMATS = self.old_TIME_INPUT_FORMATS
+ settings.USE_L10N = self.old_USE_L10N
+
+ 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")
+
+
+class CustomTimeInputFormatsTests(TestCase):
+ def setUp(self):
+ self.old_TIME_INPUT_FORMATS = settings.TIME_INPUT_FORMATS
+ settings.TIME_INPUT_FORMATS = ["%I:%M:%S %p", "%I:%M %p"]
+
+ def tearDown(self):
+ settings.TIME_INPUT_FORMATS = self.old_TIME_INPUT_FORMATS
+
+ 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(TestCase):
+ 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")
+
+
+class LocalizedDateTests(TestCase):
+ def setUp(self):
+ self.old_DATE_INPUT_FORMATS = settings.DATE_INPUT_FORMATS
+ self.old_USE_L10N = settings.USE_L10N
+
+ settings.DATE_INPUT_FORMATS = ["%d/%m/%Y", "%d-%m-%Y"]
+ settings.USE_L10N = True
+
+ activate('de')
+
+ def tearDown(self):
+ settings.DATE_INPUT_FORMATS = self.old_DATE_INPUT_FORMATS
+ settings.USE_L10N = self.old_USE_L10N
+
+ 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')
+
+ # 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")
+
+class CustomDateInputFormatsTests(TestCase):
+ def setUp(self):
+ self.old_DATE_INPUT_FORMATS = settings.DATE_INPUT_FORMATS
+ settings.DATE_INPUT_FORMATS = ["%d.%m.%Y", "%d-%m-%Y"]
+
+ def tearDown(self):
+ settings.DATE_INPUT_FORMATS = self.old_DATE_INPUT_FORMATS
+
+ 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(TestCase):
+ 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")
+
+class LocalizedDateTimeTests(TestCase):
+ def setUp(self):
+ self.old_DATETIME_INPUT_FORMATS = settings.DATETIME_INPUT_FORMATS
+ self.old_USE_L10N = settings.USE_L10N
+
+ settings.DATETIME_INPUT_FORMATS = ["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"]
+ settings.USE_L10N = True
+
+ activate('de')
+
+ def tearDown(self):
+ settings.DATETIME_INPUT_FORMATS = self.old_DATETIME_INPUT_FORMATS
+ settings.USE_L10N = self.old_USE_L10N
+
+ 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')
+
+ # 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")
+
+
+class CustomDateTimeInputFormatsTests(TestCase):
+ def setUp(self):
+ self.old_DATETIME_INPUT_FORMATS = settings.DATETIME_INPUT_FORMATS
+ settings.DATETIME_INPUT_FORMATS = ["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"]
+
+ def tearDown(self):
+ settings.DATETIME_INPUT_FORMATS = self.old_DATETIME_INPUT_FORMATS
+
+ 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(TestCase):
+ 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/regressiontests/forms/tests/media.py b/tests/regressiontests/forms/tests/media.py
new file mode 100644
index 0000000000..9a552a31da
--- /dev/null
+++ b/tests/regressiontests/forms/tests/media.py
@@ -0,0 +1,460 @@
+# -*- coding: utf-8 -*-
+from django.conf import settings
+from django.forms import TextInput, Media, TextInput, CharField, Form, MultiWidget
+from django.utils.unittest import TestCase
+
+
+class FormsMediaTestCase(TestCase):
+ # Tests for the media handling on widgets and forms
+ def setUp(self):
+ super(FormsMediaTestCase, self).setUp()
+ self.original_media_url = settings.MEDIA_URL
+ settings.MEDIA_URL = 'http://media.example.com/media/'
+
+ def tearDown(self):
+ settings.MEDIA_URL = self.original_media_url
+ super(FormsMediaTestCase, self).tearDown()
+
+ def test_construction(self):
+ # Check construction of media objects
+ m = Media(css={'all': ('path/to/css1','/path/to/css2')}, js=('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3'))
+ self.assertEqual(str(m), """
+
+
+
+""")
+
+ 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), """
+
+
+
+""")
+
+ # 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), """
+
+
+
+""")
+
+ # Media objects can be interrogated by media type
+ self.assertEqual(str(w1.media['css']), """
+""")
+
+ self.assertEqual(str(w1.media['js']), """
+
+""")
+
+ 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), """
+
+
+
+
+
+""")
+
+ # Check that media addition hasn't affected the original objects
+ self.assertEqual(str(w1.media), """
+
+
+
+""")
+
+ # 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), """
+""")
+
+ 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), """
+""")
+
+ # 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), """
+
+
+""")
+
+ 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), """
+
+
+
+
+
+""")
+
+ 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), """
+
+
+
+""")
+
+ # 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), """
+
+
+
+
+
+""")
+
+ 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), """
+
+
+""")
+
+ # 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), """
+
+
+""")
+
+ 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), """
+
+
+
+
+
+""")
+
+ 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), """
+
+
+
+""")
+
+ 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), """
+
+
+
+
+""")
+
+ 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), """
+
+
+
+
+
+""")
+
+ 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), """
+
+
+
+
+
+""")
+
+ # 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), """
+
+
+
+
+
+""")
+
+ # 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), """
+
+
+
+
+
+
+
+""")
+
+ # Media works in templates
+ from django.template import Template, Context
+ self.assertEqual(Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), """
+
+
+
+
+
+
+""")
diff --git a/tests/regressiontests/forms/tests/models.py b/tests/regressiontests/forms/tests/models.py
new file mode 100644
index 0000000000..cfdd4f4bfc
--- /dev/null
+++ b/tests/regressiontests/forms/tests/models.py
@@ -0,0 +1,161 @@
+# -*- coding: utf-8 -*-
+import datetime
+from django.core.files.uploadedfile import SimpleUploadedFile
+from django.forms import Form, ModelForm, FileField, ModelChoiceField
+from django.test import TestCase
+from regressiontests.forms.models import ChoiceModel, ChoiceOptionModel, ChoiceFieldModel, FileModel, Group, BoundaryModel, Defaults
+
+
+class ChoiceFieldForm(ModelForm):
+ class Meta:
+ model = ChoiceFieldModel
+
+
+class FileForm(Form):
+ file1 = FileField()
+
+
+class TestTicket12510(TestCase):
+ ''' It is not necessary to generate choices for ModelChoiceField (regression test for #12510). '''
+ def setUp(self):
+ self.groups = [Group.objects.create(name=name) for name in 'abc']
+
+ def test_choices_not_fetched_when_not_rendering(self):
+ def test():
+ field = ModelChoiceField(Group.objects.order_by('-name'))
+ self.assertEqual('a', field.clean(self.groups[0].pk).name)
+ # only one query is required to pull the model from DB
+ self.assertNumQueries(1, test)
+
+class ModelFormCallableModelDefault(TestCase):
+ def test_no_empty_option(self):
+ "If a model's ForeignKey has blank=False and a default, no empty option is created (Refs #10792)."
+ option = ChoiceOptionModel.objects.create(name='default')
+
+ choices = list(ChoiceFieldForm().fields['choice'].choices)
+ self.assertEquals(len(choices), 1)
+ self.assertEquals(choices[0], (option.pk, unicode(option)))
+
+ def test_callable_initial_value(self):
+ "The initial value for a callable default returning a queryset is the pk (refs #13769)"
+ obj1 = ChoiceOptionModel.objects.create(id=1, name='default')
+ obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2')
+ obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3')
+ self.assertEquals(ChoiceFieldForm().as_p(), """
Choice:
+
Choice int:
+
Multi choice: Hold down "Control", or "Command" on a Mac, to select more than one.
+
Multi choice int: Hold down "Control", or "Command" on a Mac, to select more than one.
Multi choice:
+ Hold down "Control", or "Command" on a Mac, to select more than one.
+
Multi choice int:
+ Hold down "Control", or "Command" on a Mac, to select more than one.
""")
+
+
+
+class FormsModelTestCase(TestCase):
+ def test_unicode_filename(self):
+ # FileModel with unicode filename and data #########################
+ f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')}, auto_id=False)
+ self.assertTrue(f.is_valid())
+ self.assertTrue('file1' in f.cleaned_data)
+ m = FileModel.objects.create(file=f.cleaned_data['file1'])
+ self.assertEqual(m.file.name, u'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt')
+ m.delete()
+
+ def test_boundary_conditions(self):
+ # Boundary conditions on a PostitiveIntegerField #########################
+ class BoundaryForm(ModelForm):
+ class Meta:
+ model = BoundaryModel
+
+ f = BoundaryForm({'positive_integer': 100})
+ self.assertTrue(f.is_valid())
+ f = BoundaryForm({'positive_integer': 0})
+ self.assertTrue(f.is_valid())
+ f = BoundaryForm({'positive_integer': -100})
+ self.assertFalse(f.is_valid())
+
+ def test_formfield_initial(self):
+ # Formfield initial values ########
+ # If the model has default values for some fields, they are used as the formfield
+ # initial values.
+ class DefaultsForm(ModelForm):
+ class Meta:
+ model = Defaults
+
+ self.assertEqual(DefaultsForm().fields['name'].initial, u'class default value')
+ self.assertEqual(DefaultsForm().fields['def_date'].initial, datetime.date(1980, 1, 1))
+ self.assertEqual(DefaultsForm().fields['value'].initial, 42)
+ r1 = DefaultsForm()['callable_default'].as_widget()
+ r2 = DefaultsForm()['callable_default'].as_widget()
+ self.assertNotEqual(r1, r2)
+
+ # In a ModelForm that is passed an instance, the initial values come from the
+ # instance's values, not the model's defaults.
+ foo_instance = Defaults(name=u'instance value', def_date=datetime.date(1969, 4, 4), value=12)
+ instance_form = DefaultsForm(instance=foo_instance)
+ self.assertEqual(instance_form.initial['name'], u'instance value')
+ self.assertEqual(instance_form.initial['def_date'], datetime.date(1969, 4, 4))
+ self.assertEqual(instance_form.initial['value'], 12)
+
+ from django.forms import CharField
+
+ class ExcludingForm(ModelForm):
+ name = CharField(max_length=255)
+
+ class Meta:
+ model = Defaults
+ exclude = ['name', 'callable_default']
+
+ f = ExcludingForm({'name': u'Hello', 'value': 99, 'def_date': datetime.date(1999, 3, 2)})
+ self.assertTrue(f.is_valid())
+ self.assertEqual(f.cleaned_data['name'], u'Hello')
+ obj = f.save()
+ self.assertEqual(obj.name, u'class default value')
+ self.assertEqual(obj.value, 99)
+ self.assertEqual(obj.def_date, datetime.date(1999, 3, 2))
diff --git a/tests/regressiontests/forms/tests/regressions.py b/tests/regressiontests/forms/tests/regressions.py
new file mode 100644
index 0000000000..3f69e0aa6e
--- /dev/null
+++ b/tests/regressiontests/forms/tests/regressions.py
@@ -0,0 +1,122 @@
+# -*- coding: utf-8 -*-
+from django.forms import *
+from django.utils.unittest import TestCase
+from django.utils.translation import ugettext_lazy, activate, deactivate
+
+class FormsRegressionsTestCase(TestCase):
+ def test_class(self):
+ # Tests to prevent against recurrences of earlier bugs.
+ extra_attrs = {'class': 'special'}
+
+ class TestForm(Form):
+ f1 = CharField(max_length=10, widget=TextInput(attrs=extra_attrs))
+ f2 = CharField(widget=TextInput(attrs=extra_attrs))
+
+ self.assertEqual(TestForm(auto_id=False).as_p(), u'
F1:
\n
F2:
')
+
+ def test_regression_3600(self):
+ # Tests for form i18n #
+ # There were some problems with form translations in #3600
+
+ class SomeForm(Form):
+ username = CharField(max_length=10, label=ugettext_lazy('Username'))
+
+ f = SomeForm()
+ self.assertEqual(f.as_p(), '
Username:
')
+
+ # Translations are done at rendering time, so multi-lingual apps can define forms)
+ activate('de')
+ self.assertEqual(f.as_p(), '
')
+ deactivate()
+
+ # Deep copying translated text shouldn't raise an error)
+ from django.utils.translation import gettext_lazy
+
+ class CopyForm(Form):
+ degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),)))
+
+ f = CopyForm()
+
+ def test_misc(self):
+ # There once was a problem with Form fields called "data". Let's make sure that
+ # doesn't come back.
+ class DataForm(Form):
+ data = CharField(max_length=10)
+
+ f = DataForm({'data': 'xyzzy'})
+ self.assertTrue(f.is_valid())
+ self.assertEqual(f.cleaned_data, {'data': u'xyzzy'})
+
+ # A form with *only* hidden fields that has errors is going to be very unusual.
+ class HiddenForm(Form):
+ data = IntegerField(widget=HiddenInput)
+
+ f = HiddenForm({})
+ self.assertEqual(f.as_p(), u'
(Hidden field data) This field is required.
\n
')
+ self.assertEqual(f.as_table(), u'
(Hidden field data) This field is required.
')
+
+ 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': '