Ticket #11043: inlineforeignkeys.diff

File inlineforeignkeys.diff, 4.2 KB (added by apollo13, 6 years ago)
  • django/forms/models.py

    diff --git a/django/forms/models.py b/django/forms/models.py
    index 3648a45..0324ce9 100644
    a b class BaseInlineFormSet(BaseModelFormSet): 
    749749            # The foreign key field might not be on the form, so we poke at the
    750750            # Model field to get the label, since we need that for error messages.
    751751            form.fields[self.fk.name] = InlineForeignKeyField(self.instance,
     752                to_field=self.fk.rel.field_name,
    752753                label=getattr(form.fields.get(self.fk.name), 'label', capfirst(self.fk.verbose_name))
    753754            )
    754755
    class InlineForeignKeyField(Field): 
    840841    def __init__(self, parent_instance, *args, **kwargs):
    841842        self.parent_instance = parent_instance
    842843        self.pk_field = kwargs.pop("pk_field", False)
     844        self.to_field = kwargs.pop('to_field', None)
    843845        if self.parent_instance is not None:
    844             kwargs["initial"] = self.parent_instance.pk
     846            if self.to_field:
     847                kwargs["initial"] = getattr(self.parent_instance, self.to_field)
     848            else:
     849                kwargs["initial"] = self.parent_instance.pk
    845850        kwargs["required"] = False
    846851        kwargs["widget"] = InlineForeignKeyHiddenInput
    847852        super(InlineForeignKeyField, self).__init__(*args, **kwargs)
    class InlineForeignKeyField(Field): 
    853858            # if there is no value act as we did before.
    854859            return self.parent_instance
    855860        # ensure the we compare the values as equal types.
    856         if force_unicode(value) != force_unicode(self.parent_instance.pk):
     861        orig = self.parent_instance.pk
     862        if self.to_field:
     863            orig = getattr(self.parent_instance, self.to_field)
     864        if force_unicode(value) != force_unicode(orig):
    857865            raise ValidationError(self.error_messages['invalid_choice'])
    858866        return self.parent_instance
    859867
  • tests/regressiontests/model_forms_regress/models.py

    diff --git a/tests/regressiontests/model_forms_regress/models.py b/tests/regressiontests/model_forms_regress/models.py
    index 488e2bc..00e756b 100644
    a b class Article(models.Model): 
    2828
    2929    def __unicode__(self):
    3030        return self.headline
     31
     32class User(models.Model):
     33    serial = models.IntegerField(primary_key=True)
     34    username = models.CharField(max_length=12, unique=True)
     35             
     36class UserSite(models.Model):
     37    user = models.ForeignKey(User, to_field="username")
     38    data = models.IntegerField()
  • tests/regressiontests/model_forms_regress/tests.py

    diff --git a/tests/regressiontests/model_forms_regress/tests.py b/tests/regressiontests/model_forms_regress/tests.py
    index ccc272e..bef053d 100644
    a b from datetime import date 
    22
    33from django import db
    44from django import forms
    5 from django.forms.models import modelform_factory
     5from django.forms.models import modelform_factory, inlineformset_factory
    66from django.conf import settings
    77from django.test import TestCase
    88
    9 from models import Person, Triple, FilePathModel, Article, Publication
     9from models import Person, Triple, FilePathModel, Article, Publication, User, UserSite
    1010
    1111class ModelMultipleChoiceFieldTests(TestCase):
    1212
    class ManyToManyCallableInitialTests(TestCase): 
    8888<option value="2" selected="selected">Second Book</option>
    8989<option value="3">Third Book</option>
    9090</select>  Hold down "Control", or "Command" on a Mac, to select more than one.</li>""")
     91
     92class ToFieldTest(TestCase):
     93    # regression test for #10243
     94    def test_inline_formste(self):
     95        form_set = inlineformset_factory(User, UserSite)
     96        user = User.objects.create(serial=1, username='apollo13')
     97        user.save()
     98        data = {'usersite_set-TOTAL_FORMS': u'1',
     99                'usersite_set-INITIAL_FORMS': u'0',
     100                'usersite_set-0-data': u'10',
     101                'usersite_set-0-user': u'apollo13'}
     102        f_instance = form_set(data, instance=user)
     103        f_instance.forms[0].is_valid()
     104        f_instance.save()
     105        usersite = UserSite.objects.all().values()[0]
     106        assert usersite == {'data': 10, 'user_id': u'apollo13', 'id': 1}
     107        user.delete()
Back to Top