how to limit foreign key choices by current user?

29 views
Skip to first unread message

jonathan_ou

unread,
May 18, 2007, 12:10:56 AM5/18/07
to Django users
Suppose I have a model class that has a foreign key field, something
like the following:


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?

Doug B

unread,
May 18, 2007, 2:48:10 AM5/18/07
to Django users
You can't limit choice like that. The choices specified there are
evaluated only when the model is first evaluated (module load time).

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()

jonathan_ou

unread,
May 18, 2007, 3:16:16 AM5/18/07
to Django users
Thanks that worked. Although I had to say
EForm.base_fields['apple'] .... to make it work.
Reply all
Reply to author
Forward
0 new messages