1 | diff --git a/django/forms/models.py b/django/forms/models.py
|
---|
2 | index 9e6cab8..84da2f7 100644
|
---|
3 | --- a/django/forms/models.py
|
---|
4 | +++ b/django/forms/models.py
|
---|
5 | @@ -876,7 +876,11 @@ class BaseInlineFormSet(BaseModelFormSet):
|
---|
6 | form.data[form.add_prefix(self.fk.name)] = None
|
---|
7 |
|
---|
8 | # Set the fk value here so that the form can do its validation.
|
---|
9 | - setattr(form.instance, self.fk.get_attname(), self.instance.pk)
|
---|
10 | + fk_value = self.instance.pk
|
---|
11 | + if self.fk.rel.field_name != self.fk.rel.to._meta.pk.name:
|
---|
12 | + fk_value = getattr(self.instance, self.fk.rel.field_name)
|
---|
13 | + fk_value = getattr(fk_value, 'pk', fk_value)
|
---|
14 | + setattr(form.instance, self.fk.get_attname(), fk_value)
|
---|
15 | return form
|
---|
16 |
|
---|
17 | @classmethod
|
---|
18 | diff --git a/tests/model_formsets_regress/tests.py b/tests/model_formsets_regress/tests.py
|
---|
19 | index 7d400d2..a010b9f 100644
|
---|
20 | --- a/tests/model_formsets_regress/tests.py
|
---|
21 | +++ b/tests/model_formsets_regress/tests.py
|
---|
22 | @@ -154,6 +154,18 @@ class InlineFormsetTests(TestCase):
|
---|
23 | else:
|
---|
24 | self.fail('Errors found on formset:%s' % form_set.errors)
|
---|
25 |
|
---|
26 | + def test_inline_model_with_to_field(self):
|
---|
27 | + "An inline model with a to_field of a formset with instance have working relations. Regression for #13794"
|
---|
28 | + FormSet = inlineformset_factory(User, UserSite, exclude=('is_superuser',))
|
---|
29 | +
|
---|
30 | + user = User.objects.create(username="guido", serial=1337)
|
---|
31 | + UserSite.objects.create(user=user, data=10)
|
---|
32 | + formset = FormSet(instance=user)
|
---|
33 | +
|
---|
34 | + formset[0]
|
---|
35 | + # Testing the inline model's relation
|
---|
36 | + self.assertEqual(formset[0].instance.user_id, "guido")
|
---|
37 | +
|
---|
38 | def test_formset_with_none_instance(self):
|
---|
39 | "A formset with instance=None can be created. Regression for #11872"
|
---|
40 | Form = modelform_factory(User, fields="__all__")
|
---|
41 | --
|
---|
42 | 1.7.9.5
|
---|