예제 #1
0
    def test_more_initial_than_max_num(self):
        # More initial forms than max_num will result in only the first max_num of
        # them to be displayed with no extra forms.

        initial = [
            {'name': 'Gin Tonic'},
            {'name': 'Bloody Mary'},
            {'name': 'Jack and Coke'},
        ]
        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2)
        formset = LimitedFavoriteDrinkFormSet(initial=initial)
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))

        self.assertHTMLEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name" /></td></tr>
<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" value="Bloody Mary" id="id_form-1-name" /></td></tr>""")

        # One form from initial and extra=3 with max_num=2 should result in the one
        # initial form and one extra.
        initial = [
            {'name': 'Gin Tonic'},
        ]
        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=2)
        formset = LimitedFavoriteDrinkFormSet(initial=initial)
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))

        self.assertHTMLEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name" /></td></tr>
<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""")
예제 #2
0
    def test_formset_iteration(self):
        # Regression tests for #16455 -- formset instances are iterable
        ChoiceFormset = formset_factory(Choice, extra=3)
        formset = ChoiceFormset()

        # confirm iterated formset yields formset.forms
        forms = list(formset)
        self.assertEqual(forms, formset.forms)
        self.assertEqual(len(formset), len(forms))

        # confirm indexing of formset
        self.assertEqual(formset[0], forms[0])
        try:
            formset[3]
            self.fail('Requesting an invalid formset index should raise an exception')
        except IndexError:
            pass

        # Formets can override the default iteration order
        class BaseReverseFormSet(BaseFormSet):
            def __iter__(self):
                return reversed(self.forms)

            def __getitem__(self, idx):
                return super(BaseReverseFormSet, self).__getitem__(len(self) - idx - 1)

        ReverseChoiceFormset = formset_factory(Choice, BaseReverseFormSet, extra=3)
        reverse_formset = ReverseChoiceFormset()

        # confirm that __iter__ modifies rendering order
        # compare forms from "reverse" formset with forms from original formset
        self.assertEqual(str(reverse_formset[0]), str(forms[-1]))
        self.assertEqual(str(reverse_formset[1]), str(forms[-2]))
        self.assertEqual(len(reverse_formset), len(forms))
예제 #3
0
    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.assertHTMLEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>
<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>
<tr><th><label for="id_form-2-name">Name:</label></th><td><input type="text" name="form-2-name" id="id_form-2-name" /></td></tr>""")

        # If max_num is 0 then no form is rendered at all.
        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3, max_num=0)
        formset = LimitedFavoriteDrinkFormSet()
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))

        self.assertEqual('\n'.join(form_output), "")

        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=5, max_num=2)
        formset = LimitedFavoriteDrinkFormSet()
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))

        self.assertHTMLEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>
<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""")

        # Ensure that max_num has no effect when extra is less than max_num.

        LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1, max_num=2)
        formset = LimitedFavoriteDrinkFormSet()
        form_output = []

        for form in formset.forms:
            form_output.append(str(form))

        self.assertHTMLEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" id="id_form-0-name" /></td></tr>""")
예제 #4
0
 def test_formset_nonzero(self):
     """
     Formsets with no forms should still evaluate as true.
     Regression test for #15722
     """
     ChoiceFormset = formset_factory(Choice, extra=0)
     formset = ChoiceFormset()
     self.assertEqual(len(formset.forms), 0)
     self.assertTrue(formset)
예제 #5
0
    def test_formsets_with_ordering(self):
        # FormSets with ordering ######################################################
        # We can also add ordering ability to a FormSet with an argument to
        # formset_factory. This will add a integer field to each form instance. When
        # form validation succeeds, [form.cleaned_data for form in formset.forms] will have the data in the correct
        # order specified by the ordering fields. If a number is duplicated in the set
        # of ordering fields, for instance form 0 and form 3 are both marked as 1, then
        # the form index used as a secondary ordering criteria. In order to put
        # something at the front of the list, you'd need to set it's order to 0.

        ChoiceFormSet = formset_factory(Choice, can_order=True)

        initial = [{'choice': 'Calexico', 'votes': 100}, {'choice': 'Fergie', 'votes': 900}]
        formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
        form_output = []

        for form in formset.forms:
            form_output.append(form.as_ul())

        self.assertHTMLEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li>
<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li>
<li>Order: <input type="text" name="choices-0-ORDER" value="1" /></li>
<li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li>
<li>Votes: <input type="text" name="choices-1-votes" value="900" /></li>
<li>Order: <input type="text" name="choices-1-ORDER" value="2" /></li>
<li>Choice: <input type="text" name="choices-2-choice" /></li>
<li>Votes: <input type="text" name="choices-2-votes" /></li>
<li>Order: <input type="text" name="choices-2-ORDER" /></li>""")

        data = {
            'choices-TOTAL_FORMS': '3', # the number of forms rendered
            'choices-INITIAL_FORMS': '2', # the number of forms with initial data
            'choices-MAX_NUM_FORMS': '0', # max number of forms
            'choices-0-choice': 'Calexico',
            'choices-0-votes': '100',
            'choices-0-ORDER': '1',
            'choices-1-choice': 'Fergie',
            'choices-1-votes': '900',
            'choices-1-ORDER': '2',
            'choices-2-choice': 'The Decemberists',
            'choices-2-votes': '500',
            'choices-2-ORDER': '0',
        }

        formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
        self.assertTrue(formset.is_valid())
        form_output = []

        for form in formset.ordered_forms:
            form_output.append(form.cleaned_data)

        self.assertEqual(form_output, [
            {'votes': 500, 'ORDER': 0, 'choice': 'The Decemberists'},
            {'votes': 100, 'ORDER': 1, 'choice': 'Calexico'},
            {'votes': 900, 'ORDER': 2, 'choice': 'Fergie'},
        ])
예제 #6
0
def modelformset_factory(model, form=ModelForm, formfield_callback=None,
                         formset=BaseModelFormSet,
                         extra=1, can_delete=False, can_order=False,
                         max_num=None, fields=None, exclude=None):
    """
    Returns a FormSet class for the given Django model class.
    """
    form = modelform_factory(model, form=form, fields=fields, exclude=exclude,
                             formfield_callback=formfield_callback)
    FormSet = formset_factory(form, formset, extra=extra, max_num=max_num,
                              can_order=can_order, can_delete=can_delete)
    FormSet.model = model
    return FormSet
예제 #7
0
    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), "")
예제 #8
0
    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, [])
예제 #9
0
    def test_single_form_completed(self):
        # We can just fill out one of the forms.

        data = {
            'choices-TOTAL_FORMS': '3', # the number of forms rendered
            'choices-INITIAL_FORMS': '0', # the number of forms with initial data
            'choices-MAX_NUM_FORMS': '0', # max number of forms
            'choices-0-choice': 'Calexico',
            'choices-0-votes': '100',
            'choices-1-choice': '',
            'choices-1-votes': '',
            'choices-2-choice': '',
            'choices-2-votes': '',
        }

        ChoiceFormSet = formset_factory(Choice, extra=3)
        formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
        self.assertTrue(formset.is_valid())
        self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'choice': 'Calexico'}, {}, {}])
예제 #10
0
    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.assertHTMLEqual('\n'.join(form_output), """<tr><th><label for="id_form-0-name">Name:</label></th><td><input type="text" name="form-0-name" value="Fernet and Coke" id="id_form-0-name" /></td></tr>
<tr><th><label for="id_form-1-name">Name:</label></th><td><input type="text" name="form-1-name" id="id_form-1-name" /></td></tr>""")
예제 #11
0
    def test_invalid_deleted_form_with_ordering(self):
        # Should be able to get ordered forms from a valid formset even if a
        # deleted form would have been invalid.

        class Person(Form):
            name = CharField()

        PeopleForm = formset_factory(form=Person, can_delete=True, can_order=True)

        p = PeopleForm({
            'form-0-name': '',
            'form-0-DELETE': 'on', # no name!
            'form-TOTAL_FORMS': 1,
            'form-INITIAL_FORMS': 1,
            'form-MAX_NUM_FORMS': 1
        })

        self.assertTrue(p.is_valid())
        self.assertEqual(p.ordered_forms, [])
예제 #12
0
    def test_second_form_partially_filled_2(self):
        # And once again, if we try to partially complete a form, validation will fail.

        data = {
            'choices-TOTAL_FORMS': '3', # the number of forms rendered
            'choices-INITIAL_FORMS': '0', # the number of forms with initial data
            'choices-MAX_NUM_FORMS': '0', # max number of forms
            'choices-0-choice': 'Calexico',
            'choices-0-votes': '100',
            'choices-1-choice': 'The Decemberists',
            'choices-1-votes': '', # missing value
            'choices-2-choice': '',
            'choices-2-votes': '',
        }

        ChoiceFormSet = formset_factory(Choice, extra=3)
        formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
        self.assertFalse(formset.is_valid())
        self.assertEqual(formset.errors, [{}, {'votes': ['This field is required.']}, {}])
예제 #13
0
    def test_displaying_more_than_one_blank_form(self):
        # Displaying more than 1 blank form ###########################################
        # We can also display more than 1 empty form at a time. To do so, pass a
        # extra argument to formset_factory.
        ChoiceFormSet = formset_factory(Choice, extra=3)

        formset = ChoiceFormSet(auto_id=False, prefix='choices')
        form_output = []

        for form in formset.forms:
            form_output.append(form.as_ul())

        self.assertHTMLEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" /></li>
<li>Votes: <input type="text" name="choices-0-votes" /></li>
<li>Choice: <input type="text" name="choices-1-choice" /></li>
<li>Votes: <input type="text" name="choices-1-votes" /></li>
<li>Choice: <input type="text" name="choices-2-choice" /></li>
<li>Votes: <input type="text" name="choices-2-votes" /></li>""")

        # Since we displayed every form as blank, we will also accept them back as blank.
        # This may seem a little strange, but later we will show how to require a minimum
        # number of forms to be completed.

        data = {
            'choices-TOTAL_FORMS': '3', # the number of forms rendered
            'choices-INITIAL_FORMS': '0', # the number of forms with initial data
            'choices-MAX_NUM_FORMS': '0', # max number of forms
            'choices-0-choice': '',
            'choices-0-votes': '',
            'choices-1-choice': '',
            'choices-1-votes': '',
            'choices-2-choice': '',
            'choices-2-votes': '',
        }

        formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
        self.assertTrue(formset.is_valid())
        self.assertEqual([form.cleaned_data for form in formset.forms], [{}, {}, {}])
예제 #14
0
    def test_more_initial_data(self):
        # The extra argument also works when the formset is pre-filled with initial
        # data.

        data = {
            'choices-TOTAL_FORMS': '3', # the number of forms rendered
            'choices-INITIAL_FORMS': '0', # the number of forms with initial data
            'choices-MAX_NUM_FORMS': '0', # max number of forms
            'choices-0-choice': 'Calexico',
            'choices-0-votes': '100',
            'choices-1-choice': '',
            'choices-1-votes': '', # missing value
            'choices-2-choice': '',
            'choices-2-votes': '',
        }

        initial = [{'choice': 'Calexico', 'votes': 100}]
        ChoiceFormSet = formset_factory(Choice, extra=3)
        formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
        form_output = []

        for form in formset.forms:
            form_output.append(form.as_ul())

        self.assertHTMLEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li>
<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li>
<li>Choice: <input type="text" name="choices-1-choice" /></li>
<li>Votes: <input type="text" name="choices-1-votes" /></li>
<li>Choice: <input type="text" name="choices-2-choice" /></li>
<li>Votes: <input type="text" name="choices-2-votes" /></li>
<li>Choice: <input type="text" name="choices-3-choice" /></li>
<li>Votes: <input type="text" name="choices-3-votes" /></li>""")

        # Make sure retrieving an empty form works, and it shows up in the form list

        self.assertTrue(formset.empty_form.empty_permitted)
        self.assertHTMLEqual(formset.empty_form.as_ul(), """<li>Choice: <input type="text" name="choices-__prefix__-choice" /></li>
<li>Votes: <input type="text" name="choices-__prefix__-votes" /></li>""")
예제 #15
0
    def test_empty_ordered_fields(self):
        # Ordering fields are allowed to be left blank, and if they *are* left blank,
        # they will be sorted below everything else.

        data = {
            'choices-TOTAL_FORMS': '4', # the number of forms rendered
            'choices-INITIAL_FORMS': '3', # the number of forms with initial data
            'choices-MAX_NUM_FORMS': '0', # max number of forms
            'choices-0-choice': 'Calexico',
            'choices-0-votes': '100',
            'choices-0-ORDER': '1',
            'choices-1-choice': 'Fergie',
            'choices-1-votes': '900',
            'choices-1-ORDER': '2',
            'choices-2-choice': 'The Decemberists',
            'choices-2-votes': '500',
            'choices-2-ORDER': '',
            'choices-3-choice': 'Basia Bulat',
            'choices-3-votes': '50',
            'choices-3-ORDER': '',
        }

        ChoiceFormSet = formset_factory(Choice, can_order=True)
        formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
        self.assertTrue(formset.is_valid())
        form_output = []

        for form in formset.ordered_forms:
            form_output.append(form.cleaned_data)

        self.assertEqual(form_output, [
            {'votes': 100, 'ORDER': 1, 'choice': 'Calexico'},
            {'votes': 900, 'ORDER': 2, 'choice': 'Fergie'},
            {'votes': 500, 'ORDER': None, 'choice': 'The Decemberists'},
            {'votes': 50, 'ORDER': None, 'choice': 'Basia Bulat'},
        ])
예제 #16
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from djangocg.forms import Form, CharField, IntegerField, ValidationError, DateField
from djangocg.forms.formsets import formset_factory, BaseFormSet
from djangocg.test import TestCase


class Choice(Form):
    choice = CharField()
    votes = IntegerField()


# FormSet allows us to use multiple instance of the same form on 1 page. For now,
# the best way to create a FormSet is by using the formset_factory function.
ChoiceFormSet = formset_factory(Choice)


class FavoriteDrinkForm(Form):
    name = CharField()


class BaseFavoriteDrinksFormSet(BaseFormSet):
    def clean(self):
        seen_drinks = []

        for drink in self.cleaned_data:
            if drink['name'] in seen_drinks:
                raise ValidationError('You may only specify a drink once.')

            seen_drinks.append(drink['name'])
예제 #17
0
    def test_formset_with_ordering_and_deletion(self):
        # FormSets with ordering + deletion ###########################################
        # Let's try throwing ordering and deletion into the same form.

        ChoiceFormSet = formset_factory(Choice, can_order=True, can_delete=True)

        initial = [
            {'choice': 'Calexico', 'votes': 100},
            {'choice': 'Fergie', 'votes': 900},
            {'choice': 'The Decemberists', 'votes': 500},
        ]
        formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
        form_output = []

        for form in formset.forms:
            form_output.append(form.as_ul())

        self.assertHTMLEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li>
<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li>
<li>Order: <input type="text" name="choices-0-ORDER" value="1" /></li>
<li>Delete: <input type="checkbox" name="choices-0-DELETE" /></li>
<li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li>
<li>Votes: <input type="text" name="choices-1-votes" value="900" /></li>
<li>Order: <input type="text" name="choices-1-ORDER" value="2" /></li>
<li>Delete: <input type="checkbox" name="choices-1-DELETE" /></li>
<li>Choice: <input type="text" name="choices-2-choice" value="The Decemberists" /></li>
<li>Votes: <input type="text" name="choices-2-votes" value="500" /></li>
<li>Order: <input type="text" name="choices-2-ORDER" value="3" /></li>
<li>Delete: <input type="checkbox" name="choices-2-DELETE" /></li>
<li>Choice: <input type="text" name="choices-3-choice" /></li>
<li>Votes: <input type="text" name="choices-3-votes" /></li>
<li>Order: <input type="text" name="choices-3-ORDER" /></li>
<li>Delete: <input type="checkbox" name="choices-3-DELETE" /></li>""")

        # Let's delete Fergie, and put The Decemberists ahead of Calexico.

        data = {
            'choices-TOTAL_FORMS': '4', # the number of forms rendered
            'choices-INITIAL_FORMS': '3', # the number of forms with initial data
            'choices-MAX_NUM_FORMS': '0', # max number of forms
            'choices-0-choice': 'Calexico',
            'choices-0-votes': '100',
            'choices-0-ORDER': '1',
            'choices-0-DELETE': '',
            'choices-1-choice': 'Fergie',
            'choices-1-votes': '900',
            'choices-1-ORDER': '2',
            'choices-1-DELETE': 'on',
            'choices-2-choice': 'The Decemberists',
            'choices-2-votes': '500',
            'choices-2-ORDER': '0',
            'choices-2-DELETE': '',
            'choices-3-choice': '',
            'choices-3-votes': '',
            'choices-3-ORDER': '',
            'choices-3-DELETE': '',
        }

        formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
        self.assertTrue(formset.is_valid())
        form_output = []

        for form in formset.ordered_forms:
            form_output.append(form.cleaned_data)

        self.assertEqual(form_output, [
            {'votes': 500, 'DELETE': False, 'ORDER': 0, 'choice': 'The Decemberists'},
            {'votes': 100, 'DELETE': False, 'ORDER': 1, 'choice': 'Calexico'},
        ])
        self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'ORDER': 2, 'choice': 'Fergie'}])
예제 #18
0
    def test_formset_with_deletion(self):
        # FormSets with deletion ######################################################
        # We can easily add deletion ability to a FormSet with an argument to
        # formset_factory. This will add a boolean field to each form instance. When
        # that boolean field is True, the form will be in formset.deleted_forms

        ChoiceFormSet = formset_factory(Choice, can_delete=True)

        initial = [{'choice': 'Calexico', 'votes': 100}, {'choice': 'Fergie', 'votes': 900}]
        formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
        form_output = []

        for form in formset.forms:
            form_output.append(form.as_ul())

        self.assertHTMLEqual('\n'.join(form_output), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li>
<li>Votes: <input type="text" name="choices-0-votes" value="100" /></li>
<li>Delete: <input type="checkbox" name="choices-0-DELETE" /></li>
<li>Choice: <input type="text" name="choices-1-choice" value="Fergie" /></li>
<li>Votes: <input type="text" name="choices-1-votes" value="900" /></li>
<li>Delete: <input type="checkbox" name="choices-1-DELETE" /></li>
<li>Choice: <input type="text" name="choices-2-choice" /></li>
<li>Votes: <input type="text" name="choices-2-votes" /></li>
<li>Delete: <input type="checkbox" name="choices-2-DELETE" /></li>""")

        # To delete something, we just need to set that form's special delete field to
        # 'on'. Let's go ahead and delete Fergie.

        data = {
            'choices-TOTAL_FORMS': '3', # the number of forms rendered
            'choices-INITIAL_FORMS': '2', # the number of forms with initial data
            'choices-MAX_NUM_FORMS': '0', # max number of forms
            'choices-0-choice': 'Calexico',
            'choices-0-votes': '100',
            'choices-0-DELETE': '',
            'choices-1-choice': 'Fergie',
            'choices-1-votes': '900',
            'choices-1-DELETE': 'on',
            'choices-2-choice': '',
            'choices-2-votes': '',
            'choices-2-DELETE': '',
        }

        formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
        self.assertTrue(formset.is_valid())
        self.assertEqual([form.cleaned_data for form in formset.forms], [{'votes': 100, 'DELETE': False, 'choice': 'Calexico'}, {'votes': 900, 'DELETE': True, 'choice': 'Fergie'}, {}])
        self.assertEqual([form.cleaned_data for form in formset.deleted_forms], [{'votes': 900, 'DELETE': True, 'choice': 'Fergie'}])

        # If we fill a form with something and then we check the can_delete checkbox for
        # that form, that form's errors should not make the entire formset invalid since
        # it's going to be deleted.

        class CheckForm(Form):
           field = IntegerField(min_value=100)

        data = {
            'check-TOTAL_FORMS': '3', # the number of forms rendered
            'check-INITIAL_FORMS': '2', # the number of forms with initial data
            'check-MAX_NUM_FORMS': '0', # max number of forms
            'check-0-field': '200',
            'check-0-DELETE': '',
            'check-1-field': '50',
            'check-1-DELETE': 'on',
            'check-2-field': '',
            'check-2-DELETE': '',
        }
        CheckFormSet = formset_factory(CheckForm, can_delete=True)
        formset = CheckFormSet(data, prefix='check')
        self.assertTrue(formset.is_valid())

        # If we remove the deletion flag now we will have our validation back.
        data['check-1-DELETE'] = ''
        formset = CheckFormSet(data, prefix='check')
        self.assertFalse(formset.is_valid())

        # Should be able to get deleted_forms from a valid formset even if a
        # deleted form would have been invalid.

        class Person(Form):
            name = CharField()

        PeopleForm = formset_factory(
            form=Person,
            can_delete=True)

        p = PeopleForm(
            {'form-0-name': '', 'form-0-DELETE': 'on', # no name!
             'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1,
             'form-MAX_NUM_FORMS': 1})

        self.assertTrue(p.is_valid())
        self.assertEqual(len(p.deleted_forms), 1)
예제 #19
0
 def test_empty_formset_is_valid(self):
     EmptyFsetWontValidateFormset = formset_factory(FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate)
     formset = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS':'0', 'form-TOTAL_FORMS':'0'},prefix="form")
     formset2 = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS':'0', 'form-TOTAL_FORMS':'1', 'form-0-name':'bah' },prefix="form")
     self.assertFalse(formset.is_valid())
     self.assertFalse(formset2.is_valid())
예제 #20
0
temp_storage = FileSystemStorage(location=temp_storage_location)

class Page1(forms.Form):
    name = forms.CharField(max_length=100)
    user = forms.ModelChoiceField(queryset=User.objects.all())
    thirsty = forms.NullBooleanField()

class Page2(forms.Form):
    address1 = forms.CharField(max_length=100)
    address2 = forms.CharField(max_length=100)
    file1 = forms.FileField()

class Page3(forms.Form):
    random_crap = forms.CharField(max_length=100)

Page4 = formset_factory(Page3, extra=2)

class ContactWizard(NamedUrlWizardView):
    file_storage = temp_storage

    def done(self, form_list, **kwargs):
        c = Context({
            'form_list': [x.cleaned_data for x in form_list],
            'all_cleaned_data': self.get_all_cleaned_data()
        })

        for form in self.form_list.keys():
            c[form] = self.get_cleaned_data_for_step(form)

        c['this_will_fail'] = self.get_cleaned_data_for_step('this_will_fail')
        return HttpResponse(Template('').render(c))