Ticket #10922: formset.diff

File formset.diff, 2.2 KB (added by Alex Gaynor, 16 years ago)
  • django/forms/models.py

    diff --git a/django/forms/models.py b/django/forms/models.py
    index 41380f2..08bc7dc 100644
    a b class BaseModelFormSet(BaseFormSet):  
    395395            return len(self.get_queryset())
    396396        return super(BaseModelFormSet, self).initial_form_count()
    397397
     398    def _construct_forms(self, *args, **kwargs):
     399        if self.is_bound:
     400            self._queryset_dict = dict([(o.pk, o) for o in self.get_queryset()])
     401        super(BaseModelFormSet, self)._construct_forms(*args, **kwargs)
     402        if self.is_bound:
     403            del self._queryset_dict
     404
    398405    def _construct_form(self, i, **kwargs):
    399         if i < self.initial_form_count():
     406        from django.db.models import AutoField, OneToOneField, ForeignKey
     407        if self.is_bound and i < self.initial_form_count():
     408            pk = self.data["%s-%s" % (self.add_prefix(i), self.model._meta.pk.name)]
     409            pk_field = self.model._meta.pk
     410            if isinstance(pk, OneToOneField) or isinstance(pk, ForeignKey):
     411                qs = pk.rel.to._default_manager.get_query_set()
     412            else:
     413                qs = self.model._default_manager.get_query_set()
     414            field = ModelChoiceField(qs, initial=pk, required=False, widget=HiddenInput)
     415            pk = field.clean(pk).pk
     416            kwargs['instance'] = self._queryset_dict[pk]
     417        elif i < self.initial_form_count():
    400418            kwargs['instance'] = self.get_queryset()[i]
    401419        return super(BaseModelFormSet, self)._construct_form(i, **kwargs)
    402420
    class BaseModelFormSet(BaseFormSet):  
    499517            return ((not pk.editable) or (pk.auto_created or isinstance(pk, AutoField))
    500518                or (pk.rel and pk.rel.parent_link and pk_is_editable(pk.rel.to._meta.pk)))
    501519        if pk_is_editable(pk):
    502             try:
    503                 pk_value = self.get_queryset()[index].pk
    504             except IndexError:
     520            if form.is_bound:
     521                pk_value = form.instance.pk
     522            else:
    505523                pk_value = None
    506524            if isinstance(pk, OneToOneField) or isinstance(pk, ForeignKey):
    507525                qs = pk.rel.to._default_manager.get_query_set()
Back to Top