Ticket #14574: 14574-3.diff

File 14574-3.diff, 5.6 KB (added by Claude Paroz, 13 years ago)

Remove unnecessary KeyError catching

  • django/forms/formsets.py

    diff --git a/django/forms/formsets.py b/django/forms/formsets.py
    index 9cdd051..dcd2f01 100644
    a b class BaseFormSet(StrAndUnicode):  
    122122        if self.is_bound:
    123123            defaults['data'] = self.data
    124124            defaults['files'] = self.files
    125         if self.initial:
     125        if self.initial and not 'initial' in kwargs:
    126126            try:
    127127                defaults['initial'] = self.initial[i]
    128128            except IndexError:
  • django/forms/models.py

    diff --git a/django/forms/models.py b/django/forms/models.py
    index b65f067..15d5041 100644
    a b class BaseModelFormSet(BaseFormSet):  
    418418    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
    419419                 queryset=None, **kwargs):
    420420        self.queryset = queryset
     421        self.initial_extra = kwargs.pop('initial', None)
    421422        defaults = {'data': data, 'files': files, 'auto_id': auto_id, 'prefix': prefix}
    422423        defaults.update(kwargs)
    423424        super(BaseModelFormSet, self).__init__(**defaults)
    class BaseModelFormSet(BaseFormSet):  
    448449            kwargs['instance'] = self._existing_object(pk)
    449450        if i < self.initial_form_count() and not kwargs.get('instance'):
    450451            kwargs['instance'] = self.get_queryset()[i]
     452        if i >= self.initial_form_count() and self.initial_extra:
     453            # Set initial values for extra forms
     454            try:
     455                kwargs['initial'] = self.initial_extra[i-self.initial_form_count()]
     456            except IndexError:
     457                pass
    451458        return super(BaseModelFormSet, self)._construct_form(i, **kwargs)
    452459
    453460    def get_queryset(self):
    def modelformset_factory(model, form=ModelForm, formfield_callback=None,  
    674681class BaseInlineFormSet(BaseModelFormSet):
    675682    """A formset for child objects related to a parent."""
    676683    def __init__(self, data=None, files=None, instance=None,
    677                  save_as_new=False, prefix=None, queryset=None):
     684                 save_as_new=False, prefix=None, queryset=None, **kwargs):
    678685        from django.db.models.fields.related import RelatedObject
    679686        if instance is None:
    680687            self.instance = self.fk.rel.to()
    class BaseInlineFormSet(BaseModelFormSet):  
    687694            queryset = self.model._default_manager
    688695        qs = queryset.filter(**{self.fk.name: self.instance})
    689696        super(BaseInlineFormSet, self).__init__(data, files, prefix=prefix,
    690                                                 queryset=qs)
     697                                                queryset=qs, **kwargs)
    691698
    692699    def initial_form_count(self):
    693700        if self.save_as_new:
  • docs/topics/forms/formsets.txt

    diff --git a/docs/topics/forms/formsets.txt b/docs/topics/forms/formsets.txt
    index 37c3067..b524c24 100644
    a b Formsets can also be indexed into, which returns the corresponding form. If you  
    5353override ``__iter__``, you will need to also override ``__getitem__`` to have
    5454matching behavior.
    5555
     56.. _formsets-initial-data:
     57
    5658Using initial data with a formset
    5759---------------------------------
    5860
  • docs/topics/forms/modelforms.txt

    diff --git a/docs/topics/forms/modelforms.txt b/docs/topics/forms/modelforms.txt
    index 832a3ac..e047b6e 100644
    a b exclude::  
    617617
    618618    >>> AuthorFormSet = modelformset_factory(Author, exclude=('birth_date',))
    619619
     620Providing initial values
     621------------------------
     622
     623    .. versionadded:: 1.4
     624
     625As with regular formsets, it is possible to :ref:`specify initial data
     626<formsets-initial-data>` for forms in the formset. However, with model formsets
     627the initial values only apply to extra forms, those which are not bound with an
     628existing object instance.
     629
     630
    620631.. _saving-objects-in-the-formset:
    621632
    622633Saving objects in the formset
  • tests/regressiontests/model_formsets_regress/tests.py

    diff --git a/tests/regressiontests/model_formsets_regress/tests.py b/tests/regressiontests/model_formsets_regress/tests.py
    index 35a794a..b1ad201 100644
    a b class InlineFormsetTests(TestCase):  
    204204            ["<Host: matrix.de.eu.dal.net>", "<Host: tranquility.hub.dal.net>"]
    205205            )
    206206
     207    def test_initial_data(self):
     208        user = User.objects.create(username="bibi", serial=1)
     209        usersite = UserSite.objects.create(user=user, data=7)
     210        Form = modelform_factory(User)
     211        FormSet = inlineformset_factory(User, UserSite, extra=2)
     212
     213        formset = FormSet(instance=user, initial=[{'data': 41}, {'data': 42}])
     214        self.assertEqual(formset.forms[0].initial['data'], 7)
     215        self.assertEqual(formset.extra_forms[0].initial['data'], 41)
     216        self.assertTrue(u'value="42"' in formset.extra_forms[1].as_p())
     217
     218
    207219class FormsetTests(TestCase):
    208220    def test_error_class(self):
    209221        '''
    class FormsetTests(TestCase):  
    230242            self.assertTrue(isinstance(form.errors, ErrorDict))
    231243            self.assertTrue(isinstance(form.non_field_errors(), ErrorList))
    232244
     245    def test_initial_data(self):
     246        user = User.objects.create(username="bibi", serial=1)
     247        Formset = modelformset_factory(User, extra=2)
     248        formset = Formset(initial=[{'username': u'apollo11'}, {'username': u'apollo12'}])
     249        self.assertEqual(formset.forms[0].initial['username'], "bibi")
     250        self.assertEqual(formset.extra_forms[0].initial['username'], "apollo11")
     251        self.assertTrue(u'value="apollo12"' in formset.extra_forms[1].as_p())
     252
    233253class CustomWidget(forms.CharField):
    234254    pass
    235255
Back to Top