Search code examples
djangoassigndjango-usersdjango-managersusergroups

how to assign a user in a particular group in the registration process itself in django


I have created a custom user creation form in which I included a choice field 'Company' & 'Truck' so that user can be identified according to the field. Here is my registration pageenter image description here I also created two groups Truck & Company via admin page. I want to assign a specific user in the registration process to the particular group so that, I later want to give the permissions to a particular user on their group basis. I tried by creating a def as assign_group in EmailUserManager. But not working as I wanted. Please help me how can I assign the users to the particular groups.

models.py:

 """User models."""
import django
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager, PermissionsMixin, Group)
from django.core.mail import send_mail
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model


class EmailUserManager(BaseUserManager):

"""Custom manager for EmailUser."""

def _create_user(self, email, password,
                 is_staff, is_superuser, **extra_fields):
    """Create and save an EmailUser with the given email and password.

    :param str email: user email
    :param str password: user password
    :param bool is_staff: whether user staff or not
    :param bool is_superuser: whether user admin or not
    :return custom_user.models.EmailUser user: user
    :raise ValueError: email is not set

    """
    now = timezone.now()
    if not email:
        raise ValueError('The given email must be set')
    email = self.normalize_email(email)
    is_active = extra_fields.pop("is_active", True)
    user = self.model(email=email, is_staff=is_staff, is_active=is_active,
                      is_superuser=is_superuser, last_login=now,
                      date_joined=now, **extra_fields)
    user.set_password(password)
    user.save(using=self._db)
    return user

def create_user(self, email, password=None, **extra_fields):
    """Create and save an EmailUser with the given email and password.

    :param str email: user email
    :param str password: user password
    :return custom_user.models.EmailUser user: regular user

    """
    is_staff = extra_fields.pop("is_staff", False)
    return self._create_user(email, password, is_staff, False,
                             **extra_fields)

def create_superuser(self, email, password, **extra_fields):
    """Create and save an EmailUser with the given email and password.

    :param str email: user email
    :param str password: user password
    :return custom_user.models.EmailUser user: admin user

    """
    return self._create_user(email, password, True, True,
                             **extra_fields)


class EmailUser(AbstractEmailUser):

"""
Concrete class of AbstractEmailUser.

Use this if you don't need to extend EmailUser.

"""
CHOICES = (('Truck', 'Truck'),('Company', 'Company'),)
Label = models.CharField(choices=CHOICES, max_length=20)

def assign_group(self, email, password, **extra_fields):
    user = self.model(email=email, is_staff=is_staff, is_active=is_active,
                      is_superuser=is_superuser, last_login=now,
                      date_joined=now, Label=label, **extra_fields)
    if user.Label == 'Truck':
        g1 = Group.objects.get(name=Truck)
        g1.user_set.add(TRUCK_USER)
        user_group.save()
        user.save(using=self._db)
        return user
    elif user.Label == 'Company':
        g2 = Group.objects.get(name=Company)
        g2.user_set.add(COMPANY_USER)
        user_group.save()
        user.save(using=self._db)
        return user
class Meta(AbstractEmailUser.Meta):
    swappable = 'AUTH_USER_MODEL'

forms.py:

 class EmailUserCreationForm(forms.ModelForm):

"""A form for creating new users.

Includes all the required fields, plus a repeated password.

"""

error_messages = {
    'duplicate_email': _("A user with that email already exists."),
    'password_mismatch': _("The two password fields didn't match."),
}

password1 = forms.CharField(
    label=_("Password"),
    widget=forms.PasswordInput)
password2 = forms.CharField(
    label=_("Password confirmation"),
    widget=forms.PasswordInput,
    help_text=_("Enter the same password as above, for verification."))

CHOICES= (('Truck', 'Truck'),('Company', 'Company'),)
Label = forms.ChoiceField(choices=CHOICES, label='Label', widget=forms.RadioSelect())

class Meta:
    model = get_user_model()
    fields = ('email', 'password1', 'password2', 'Label',)

def __init__(self, *args, **kwargs):
    super(EmailUserCreationForm, self).__init__(*args, **kwargs)
    self.fields.keyOrder = ['email', 'password1', 'password2', 'Label']

def clean_email(self):
    """Clean form email.

    :return str email: cleaned email
    :raise forms.ValidationError: Email is duplicated

    """
    # Since EmailUser.email is unique, this check is redundant,
    # but it sets a nicer error message than the ORM. See #13147.
    email = self.cleaned_data["email"]
    try:
        get_user_model()._default_manager.get(email=email)
    except get_user_model().DoesNotExist:
        return email
    raise forms.ValidationError(
        self.error_messages['duplicate_email'],
        code='duplicate_email',
    )

def clean_password2(self):
    """Check that the two password entries match.

    :return str password2: cleaned password2
    :raise forms.ValidationError: password2 != password1

    """
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError(
            self.error_messages['password_mismatch'],
            code='password_mismatch',
        )
    return password2

def save(self, commit=True):
    """Save user.

    Save the provided password in hashed format.

    :return custom_user.models.EmailUser: user

    """
    user = super(EmailUserCreationForm, self).save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()
    return user

Solution

  • Answer before question edit:

    Find the group object by Label and add user object to that group.

    from django.contrib.auth.models import Group
    g = Group.objects.get(name=LABEL_NAME) 
    g.user_set.add(YOUR_USER)
    

    Update 1:

    Groups are like categories. You just put users in some categories. When we talk about group permissions, we usually handle them via utility functions such as:

    def is_truck(user):
        return user.groups.filter(name='truck').exists()
    
    def is_company(user):
        return user.groups.filter(name='company').exists()
    

    or you can make properties on user objects.