views:

56

answers:

3

Hi all,

I have a database which keeps track of interaction between two different teams (represented in the admin interface by two different groups). For some fields, i have a foreignkey to Users database, and i would like to limit the dropdown people to only the specific groups.

If anyone have any suggestions, it would be much appreciated!

Jason

+2  A: 

You can change the underlaying queryset for the form field: http://stackoverflow.com/questions/291945/how-do-i-filter-foreignkey-choices-in-a-django-modelform

lazerscience
It seems to say that it should be done in the view, but i'm not sure how to access the view, the only thing i have access to is the model class and the modeladmin class. Any particular directional suggestions would be greatly appreciated!
FurtiveFelon
You should use a custom form and do it in the form's `__init__`! def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields["user"].queryset = User.objects.filter(...)
lazerscience
+1  A: 

To override the choices for a foreign key field in Django admin app, write a formfield_for_foreignkey method.

Alasdair
+1  A: 

You're looking for limit_choices_to.

Ignacio Vazquez-Abrams
Hey thanks for your answer! However, i think the user-groups relationship resides on different tables in django admin, how would i filter in that case?
FurtiveFelon
With `Q` objects. `Q(group__icontains=u'user')`
Ignacio Vazquez-Abrams
Hey Ignacio, I'm still kinda confused on how to do this. After digging through the code for auth module further, i have found that groups is defined in User class as follows: groups = models.ManyToManyField(Group, verbose_name=_('groups'), blank=True,). The query is based on Users, so i would like to check whether the current User in question is in group "Legal". Note that the Group model have a ID, so the name is not stored in User directly. Thank you very much for all your help!
FurtiveFelon
`ForeignKey(User, limit_choices_to={'groups__name': u'Legal'}, ...)`
Ignacio Vazquez-Abrams
thanks a lot for all your help!
FurtiveFelon