Permalink
Browse files

[0.5.X] Fixed #9462 -- Set the instance in an inline formset correctl…

…y so that None does not get passed through to the queryset. Thanks tobias and copelco for the ticket.

Backport of r9293 from trunk.

git-svn-id: http://code.djangoproject.com/svn/django/branches/releases/1.0.X@9294 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
1 parent 84216ef commit 38d9b0919bb07f4dcfcf22a9013b1a711f54ab89 @brosner brosner committed Oct 28, 2008
Showing with 30 additions and 1 deletion.
  1. +4 −1 django/forms/models.py
  2. +26 −0 tests/modeltests/model_formsets/models.py
View
5 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()
View
26 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 @@ class Membership(models.Model):
>>> 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()
+[<Player: Bobby>]
+
"""}

0 comments on commit 38d9b09

Please sign in to comment.