is there a way to assign users in groups from django views?

You can use ModelChoiceField to include select widget in your form. So please try this code:

forms.py

from django.contrib.auth.models import Group
from django.forms import ModelForm, ModelChoiceField

from app.model import CustomUser


class UserForm(ModelForm):

    class Meta:
        model = CustomUser
        fields = [
            'email',
            'password',
        ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['group'] = ModelChoiceField(
            queryset=Group.objects.all(),
            empty_label='No group'
        )

Change CustomUserManager.create_user method in model.py

from django.contrib.auth.models import Group


class CustomUserManager(BaseUserManager):

    def create_user(self, email: str, password: str, group: Group, **extra_fields):
        if not email:
            raise ValueError(_('The Email must be set'))

        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()

        if group is not None:
            group.user_set.add(user)

        return user

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top