'Limit Django users to one single group
I'm rather surprised that this hasn't been asked before, but I need to limit my Users in Django to only belong to one single Group. How would I do this?
Solution 1:[1]
One option can be that in your view or form, before you add more groups to the user you make a validation:
if user.groups.exists():
for g in user.groups.all():
user.groups.remove(g)
user.groups.add(group_to_add)
Solution 2:[2]
You need to override the Groups field widget :
groups = forms.ModelMultipleChoiceField(
queryset=Group.objects.all(),
widget=forms.SelectMultiple
)
and then remove the 'multiple' attribute using Javascript :
$(document).ready(function(){
$("#id_groups").removeAttr("multiple");
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | elsadek |