2016-07-07 7 views
0

사용자 필드에 따라 사용자를 식별 할 수 있도록 'Company'& '트럭'선택 필드가 포함 된 사용자 정의 사용자 작성 양식을 만들었습니다. 들. 여기에 내 등록 페이지입니다 enter image description here 나는 또한 두 그룹의 트럭을 만들었습니다 & 회사를 통해 관리 페이지. 특정 그룹에 등록 프로세스의 특정 사용자를 지정하여 나중에 그룹 단위로 특정 사용자에게 사용 권한을 부여하려고합니다. EmailUserManager에서 def로 assign_group을 작성했습니다. 하지만 내가 원하는대로 일하지 않아. 특정 그룹에 사용자를 할당하는 방법을 알려주십시오.django에서 등록 프로세스 자체의 특정 그룹에 사용자를 할당하는 방법

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 

답변

0

답변 :

이 라벨에 의해 그룹 개체를 찾아 해당 그룹에 사용자 개체를 추가합니다.

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

업데이트 1 :

그룹 카테고리 같다. 사용자를 일부 카테고리에 배치하기 만하면됩니다. 그룹 권한에 관해서는 일반적으로

과 같은 유틸리티 기능을 통해 처리하거나 사용자 개체에 대한 속성을 만들 수 있습니다.

+0

나는 그룹을 할당하고 관리하기 위해 emailusermager에서 일부 사용 권한을 만들어야합니까? 그렇다면 무엇을해야합니까? – vanam

+0

친절한 답변을 주셔서 감사합니다. 그렇다면 사용자 등록 절차를 거쳐 직접 만든 그룹에 일부 사용자를 추가하는 방법은 무엇입니까? – vanam

+0

저는 장고를 처음 사용합니다. 내 코드에 g = Group.objects.get (name = LABEL_NAME) g.user_set.add (YOUR_USER)를 추가 한 후에도 등록 된 사용자를 spcific 그룹에 할당 할 수 없었습니다. 어떻게 해결할 수 있습니까? – vanam