Ticket #14574: 14574.diff

File 14574.diff, 2.0 KB (added by Claude Paroz, 13 years ago)

Initial values for model formsets

  • django/forms/formsets.py

    diff --git a/django/forms/formsets.py b/django/forms/formsets.py
    index 04057a1..a2c886c 100644
    a b class BaseFormSet(StrAndUnicode):  
    119119        if self.is_bound:
    120120            defaults['data'] = self.data
    121121            defaults['files'] = self.files
    122         if self.initial:
     122        if self.initial and not 'initial' in kwargs:
    123123            try:
    124124                defaults['initial'] = self.initial[i]
    125             except IndexError:
     125            except (IndexError, KeyError):
    126126                pass
    127127        # Allow extra forms to be empty.
    128128        if i >= self.initial_form_count():
  • django/forms/models.py

    diff --git a/django/forms/models.py b/django/forms/models.py
    index 254cca3..1fbcefc 100644
    a b class BaseModelFormSet(BaseFormSet):  
    447447            kwargs['instance'] = self._existing_object(pk)
    448448        if i < self.initial_form_count() and not kwargs.get('instance'):
    449449            kwargs['instance'] = self.get_queryset()[i]
     450        if i >= self.initial_form_count() and self.initial:
     451            # Set initial values for extra forms
     452            try:
     453                kwargs['initial'] = self.initial[i-self.initial_form_count()]
     454            except IndexError:
     455                pass
    450456        return super(BaseModelFormSet, self)._construct_form(i, **kwargs)
    451457
    452458    def get_queryset(self):
  • docs/topics/forms/modelforms.txt

    diff --git a/docs/topics/forms/modelforms.txt b/docs/topics/forms/modelforms.txt
    index 07c7b02..79a0345 100644
    a b exclude::  
    613613
    614614    >>> AuthorFormSet = modelformset_factory(Author, exclude=('birth_date',))
    615615
     616Providing initial values
     617------------------------
     618
     619Like with regular formsets, it is possible to specify initial data for forms
     620in the formset. However, with model formsets the initial values only apply to
     621extra forms, those which are not bound with an existing object instance.
     622
     623
    616624.. _saving-objects-in-the-formset:
    617625
    618626Saving objects in the formset
Back to Top