Home > Mobile >  How Can I get a Particular User Group Name in Django Form Query
How Can I get a Particular User Group Name in Django Form Query

Time:06-28

I have a Django form with a Drop Down from User Groups which is Created from Django Admin Panel. I have 3 groups with various permissions so in this form I want to get only the Group named 'Guest' from the drop down and disabled. What is the best way of doing it.

Below is what I have tried but I am getting the following errors: ImportError: cannot import name 'getgroups' from 'os'

class GuestUserForm(UserCreationForm):
    email = forms.EmailField
    group = forms.ModelChoiceField(queryset=Group.objects.get('Guest'),
                               required=True)

class Meta:
    model = User
    fields = ['username', 'email', 'password1', 'password2', 'group']

CodePudding user response:

The standard User model has a field named groups, so plural. You can work with a ModelMultipleChoiceField [Django-doc] and only retain a single element: the group named Guest:

class GuestUserForm(UserCreationForm):
    email = forms.EmailField()
    group = forms.ModelMultipleChoiceField(
        queryset=Group.objects.filter(name='Guest'),
        initial=Group.objects.filter(name='Guest'),
        disabled=True
    )

class Meta:
    model = User
    fields = ['username', 'email', 'groups']
  • Related