如何在django中的注册过程本身的特定组中分配用户 [英] how to assign a user in a particular group in the registration process itself in django

查看:288
本文介绍了如何在django中的注册过程本身的特定组中分配用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



models.py:

 $
import django
from django.contrib.auth.models import(
AbstractBaseUser,BaseUserManager,PermissionsMixin,Group)
从django.core.mail导入send_mail
从django.db导入模型
从django.utils导入时区
从django.utils.translation导入ugettext_lazy为_
从django .contrib.auth.models import来自django.contrib.auth的用户
导入get_user_model


class EmailUserManager(BaseUserManager):

自定义经理EmailUser。

def _create_user(self,email,password,
is_staff,is_superuser,** extra_fields):
创建并保存EmailUser给定的电子邮件和密码

:param str电子邮件:用户电子邮件
:param str密码:用户密码
:param bool is_staff:是否用户工作人员
:param bool is_superuser:是否用户admin
:return custom_user.models.EmailUser用户:user
:raise ValueError:未设置电子邮件


now = timezone.now()
如果不是电子邮件:
raise ValueError('给定的电子邮件必须设置')
email = self.normalize_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 =现在,** extra_fields)
user.set_password(密码)
user.save(using = self._db)
返回用户

def create_user(self,email ,password = None,** extra_fields):
创建并保存具有给定电子邮件和密码的EmailUser。

:param str email:user email
:param str password:用户密码
:return custom_user.models.EmailUser用户:普通用户


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):
创建并保存具有给定电子邮件和密码的EmailUser。

:param str email:user email
:param str password:用户密码
:return custom_user.models.EmailUser用户:admin user


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


class EmailUser(AbstractEmailUser):


AbstractEmailUser的具体类。

如果不需要扩展EmailUser,请使用此选项。


选择=(('卡车','卡车'),('公司','公司'),)
Label = models.CharField = 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)
如果user.Label =='卡车':
g1 =组.objects.get(name = Truck)
g1.user_set.add(TRUCK_USER)
user_group.save()
user.save(using = self._db)
返回用户
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):

用于创建新用户的表单。

包含所有必填字段,加上重复的密码。



error_messages = {
'duplicate_email':_(具有该电子邮件的用户已存在),
'password_mismatch ':_(两个密码字段不匹配),
}

password1 = forms.CharField(
label = _(密码),
widget = forms.PasswordInput
password2 = forms.CharField(
label = _(密码确认),
widget = forms.PasswordInput,
help_text = _ (输入与上述相同的密码进行验证)

选择=(('卡车','卡车'),('公司','公司'))
Label = forms.ChoiceField(choices = CHOICES,label ='Label',widget = forms.RadioSelect())

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

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

def clean_email(self):
清洁表单电子邮件。

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


#由于EmailUser.email是唯一的,这个检查是多余的,
#,但它设置了比ORM更好的错误信息,参见#13147。
email = self.cleaned_data [email]
try:
get_user_model()._ default_manager.get(email = email)
除了get_user_model().NotExist:
返回电子邮件
raise forms.ValidationError(
self.error_messages ['duplicate_email'] ,
code ='duplicate_email',


def clean_password2(self):
检查两个密码条目是否匹配。

:return str password2:已清除密码2
:raise forms.ValidationError:password2!= password1


password1 = self.cleaned_data。 get(password1)
password2 = self.cleaned_data.get(password2)
如果password1和password2和password1!= password2:
raise forms.ValidationError(
self .error_messages ['password_mismatch'],
code ='password_mismatch',

return password2

def save(self,commit = True):
保存用户。

以哈希格式保存提供的密码。

:return custom_user.models.EmailUser:user


user = super(EmailUserCreationForm,self).save(commit = False)
user.set_password(self.cleaned_data [password1])
如果提交:
user.save()
返回用户


解决方案

在问题编辑之前回答:



标签并将用户对象添加到该组。

  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(n ame ='company')。exists()

或者您可以对用户对象进行属性。 p>

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 page 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

解决方案

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.

这篇关于如何在django中的注册过程本身的特定组中分配用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆