如何在django中的注册过程中为特定组中的用户分配

时间:2016-07-07 13:42:22

标签: django assign django-users django-managers usergroups

我创建了一个自定义用户创建表单,其中包含了一个选择字段' Company' &安培; '卡车'这样可以根据现场识别用户。这是我的注册页面enter image description here我还创建了两组Truck&公司通过管理页面。我想在注册过程中将特定用户分配给特定组,以便我以后想要以组为基础向特定用户授予权限。我尝试在EmailUserManager中创建def as assign_group。但不按我的意愿工作。请帮助我如何将用户分配到特定组。

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

1 个答案:

答案 0 :(得分:0)

在编辑问题之前回答:

按Label查找组对象,并将用户对象添加到该组。

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

更新1:

群组就像是类别。您只需将用户置于某些类别。当我们谈论组权限时,我们通常通过实用程序函数来处理它们,例如:

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

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

或者您可以在用户对象上创建属性。