diff --git a/django/forms/models.py b/django/forms/models.py index 180aec60db..0c98f52660 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -446,7 +446,10 @@ class BaseInlineFormSet(BaseModelFormSet): def __init__(self, data=None, files=None, instance=None, save_as_new=False, prefix=None): from django.db.models.fields.related import RelatedObject - self.instance = instance + if instance is None: + self.instance = self.model() + else: + self.instance = instance self.save_as_new = save_as_new # is there a better way to get the object descriptor? self.rel_name = RelatedObject(self.fk.rel.to, self.model, self.fk).get_accessor_name() diff --git a/tests/modeltests/model_formsets/models.py b/tests/modeltests/model_formsets/models.py index 3c97931595..215f35b59a 100644 --- a/tests/modeltests/model_formsets/models.py +++ b/tests/modeltests/model_formsets/models.py @@ -107,6 +107,17 @@ class Membership(models.Model): date_joined = models.DateTimeField(default=datetime.datetime.now) karma = models.IntegerField() +# models for testing a null=True fk to a parent +class Team(models.Model): + name = models.CharField(max_length=100) + +class Player(models.Model): + team = models.ForeignKey(Team, null=True) + name = models.CharField(max_length=100) + + def __unicode__(self): + return self.name + __test__ = {'API_TESTS': """ >>> from datetime import date @@ -701,4 +712,19 @@ False >>> formset.is_valid() True +# inlineformset_factory tests with fk having null=True. see #9462. +# create some data that will exbit the issue +>>> team = Team.objects.create(name=u"Red Vipers") +>>> Player(name="Timmy").save() +>>> Player(name="Bobby", team=team).save() + +>>> PlayerInlineFormSet = inlineformset_factory(Team, Player) +>>> formset = PlayerInlineFormSet() +>>> formset.get_queryset() +[] + +>>> formset = PlayerInlineFormSet(instance=team) +>>> formset.get_queryset() +[] + """}