class example_model(models.Model):
apple = models.ForeignKey(Apple)
owner = models.ForeignKey(User)
where Apple is created by authenticated users. So at any given time,
there may be multiple Apples created by different users.
When I create a form via form_for_model(example_model), however, all
possible Apples created by different users will be visible.
My question is how do I limit the Apple choices in the form to only
show the Apples the the current user created? I tried to do
apple = models.ForeignKey(Apple, limit_choices_to={'owner__exact':
self.owner}),
But django says 'self' is not defined . Can anyone tell me what I
should do?
What you need to do is limit the options displayed to the user via
form choices assigned in your view.
So you might do something like this (I'm half asleep, but hopefully
you get the idea):
user=User.objects.get(pk=1)
EForm = form_for_model(example_model)
EForm.fields['apple'].choices= \
[(a.id,a.name) for a in user.example_model_set.objects.all()]
form=EForm()
Although now that I look at your model, I'm not sure I get what you
are doing. Something like this makes more sense unless I'm
misunderstanding:
Assuming an apple has a single owner....
class Apple(models.Model):
owner=models.ForeignKey(User)
apple_field1 = models.IntegerField()
apple_field2 = models.IntegerField()
Assuming an apple has a multiple owners and owners have multiple
apples....
class Apple(models.Model):
owner=models.ManyToManyField(User) # Let django make the
intermediate table for you
apple_field1 = models.IntegerField()
apple_field2 = models.IntegerField()