Ticket #13794: to_field_formsets.patch

File to_field_formsets.patch, 1.8 KB (added by anonymous, 12 years ago)
  • django/forms/models.py

    diff --git a/django/forms/models.py b/django/forms/models.py
    index 27c246b..b1d4afd 100644
    a b class BaseInlineFormSet(BaseModelFormSet):  
    716716            form.data[form.add_prefix(self.fk.name)] = None
    717717
    718718        # Set the fk value here so that the form can do its validation.
    719         setattr(form.instance, self.fk.get_attname(), self.instance.pk)
     719        fk_value = self.instance.pk
     720        if self.fk.rel.field_name != self.fk.rel.to._meta.pk.name:
     721            fk_value = getattr(self.instance, self.fk.rel.field_name)
     722            fk_value = getattr(fk_value, 'pk', fk_value)
     723        setattr(form.instance, self.fk.get_attname(), fk_value)
    720724        return form
    721725
    722726    @classmethod
  • 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 8cadcfc..78f9ce1 100644
    a b class InlineFormsetTests(TestCase):  
    154154        else:
    155155            self.fail('Errors found on formset:%s' % form_set.errors)
    156156
     157    def test_inline_model_with_to_field(self):
     158        "An inline model with a to_field of a formset with instance have working relations. Regression for #13794"
     159        FormSet = inlineformset_factory(User, UserSite)
     160
     161        user = User.objects.create(username="guido", serial=1337)
     162        UserSite.objects.create(user=user, data=10)
     163        formset = FormSet(instance=user)
     164
     165        formset[0]
     166
     167        # Testing the inline model's relation
     168        self.assertEqual(formset[0].instance.user_id, "guido")
     169
    157170    def test_formset_with_none_instance(self):
    158171        "A formset with instance=None can be created. Regression for #11872"
    159172        Form = modelform_factory(User)
Back to Top