Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading