14

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!

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
FurtiveFelon
  • 14,714
  • 27
  • 76
  • 97

3 Answers3

25

You're looking for limit_choices_to.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 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 Jun 18 '10 at 19:43
  • With `Q` objects. `Q(group__icontains=u'user')` – Ignacio Vazquez-Abrams Jun 18 '10 at 19:46
  • 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 Jun 18 '10 at 20:33
  • 1
    `ForeignKey(User, limit_choices_to={'groups__name': u'Legal'}, ...)` – Ignacio Vazquez-Abrams Jun 18 '10 at 20:43
  • 5
    What if I want it to be filtered not based on a constant, but based on another model field??? Meaning: What if I want access to 'self' in this Q object? – Francisco Apr 21 '15 at 01:57
  • This doesn't let you access the request if you want i.e. to filter objects based on the current user. use answers from https://stackoverflow.com/questions/10179129 to do that. – sox supports the mods Nov 12 '18 at 16:26
3

You can change the underlaying queryset for the form field: How do I filter ForeignKey choices in a Django ModelForm?

Community
  • 1
  • 1
Bernhard Vallant
  • 49,468
  • 20
  • 120
  • 148
  • 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 Jun 17 '10 at 18:55
  • 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(...) – Bernhard Vallant Jun 17 '10 at 19:50
3

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

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Another alternative, in case the choices depend on the model instance: https://stackoverflow.com/a/949290 – djvg Jul 23 '20 at 13:25