' % 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/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/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/tests.py b/tests/regressiontests/forms/localflavortests.py
similarity index 79%
rename from tests/regressiontests/forms/tests.py
rename to tests/regressiontests/forms/localflavortests.py
index fbf3158ca1..30c06ef79a 100644
--- a/tests/regressiontests/forms/tests.py
+++ b/tests/regressiontests/forms/localflavortests.py
@@ -1,7 +1,4 @@
# -*- coding: utf-8 -*-
-from extra import tests as extra_tests
-from forms import tests as form_tests
-from error_messages import tests as custom_error_message_tests
from localflavor.ar import tests as localflavor_ar_tests
from localflavor.at import tests as localflavor_at_tests
from localflavor.au import tests as localflavor_au_tests
@@ -32,25 +29,10 @@ from localflavor.uk import tests as localflavor_uk_tests
from localflavor.us import tests as localflavor_us_tests
from localflavor.uy import tests as localflavor_uy_tests
from localflavor.za import tests as localflavor_za_tests
-from regressions import tests as regression_tests
-from util import tests as util_tests
-from widgets import tests as widgets_tests
-from formsets import tests as formset_tests
-from media import media_tests
-
-from formsets import FormsetAsFooTests
-from fields import FieldsTests
-from validators import TestFieldWithValidators
-from widgets import WidgetTests, ClearableFileInputTests
from localflavor.be import BETests
-from input_formats import *
-
__test__ = {
- 'extra_tests': extra_tests,
- 'form_tests': form_tests,
- 'custom_error_message_tests': custom_error_message_tests,
'localflavor_ar_tests': localflavor_ar_tests,
'localflavor_at_tests': localflavor_at_tests,
'localflavor_au_tests': localflavor_au_tests,
@@ -80,11 +62,6 @@ __test__ = {
'localflavor_us_tests': localflavor_us_tests,
'localflavor_uy_tests': localflavor_uy_tests,
'localflavor_za_tests': localflavor_za_tests,
- 'regression_tests': regression_tests,
- 'formset_tests': formset_tests,
- 'media_tests': media_tests,
- 'util_tests': util_tests,
- 'widgets_tests': widgets_tests,
}
if __name__ == "__main__":
diff --git a/tests/regressiontests/forms/media.py b/tests/regressiontests/forms/media.py
deleted file mode 100644
index d715fb4d80..0000000000
--- a/tests/regressiontests/forms/media.py
+++ /dev/null
@@ -1,385 +0,0 @@
-# -*- coding: utf-8 -*-
-# Tests for the media handling on widgets and forms
-
-media_tests = r"""
->>> from django.forms import TextInput, Media, TextInput, CharField, Form, MultiWidget
->>> from django.conf import settings
->>> ORIGINAL_MEDIA_URL = settings.MEDIA_URL
->>> settings.MEDIA_URL = 'http://media.example.com/media/'
-
-# Check construction of media objects
->>> m = Media(css={'all': ('path/to/css1','/path/to/css2')}, js=('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3'))
->>> print m
-
-
-
-
-
-
->>> 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(),"""
+
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': '