Selecting specific users
I have a a model that stores users:
class SubItem(models.Model):
created = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User)
I have a group in the auth admin section c开发者_StackOverflow中文版alled 'advisors'. How do I only show the advisors in the pulldown that django creates. (I have a feeling I have to override the init in forms.py)
You are looking for the limit_choices_to
parameter.
Example:
class SubItem(models.Model):
created = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User,
limit_choices_to={'group': 'advisors'})
I found out from this link that only selecting users in a set group needs to be enforced at the form level
class SubItemForm(ModelForm):
def __init__(self,user,*args,**kwargs):
super(SubItemForm, self).__init__(*args, **kwargs)
self.fields['advisor'].queryset = User.objects.filter(groups__name='advisor')
I hope this helps someone
精彩评论