私は、ユーザフィールドを 'Company' & 'Truck'フィールドに含めてカスタムユーザ作成フォームを作成しました。フィールド。ここに私の登録ページ私はまた2つのグループを作成しましたトラック&会社の管理ページを介して。特定のユーザーにグループ単位でアクセス許可を与えたいので、登録プロセスで特定のユーザーを特定のグループに割り当てる必要があります。私はEmailUserManagerのassign_groupとしてdefを作成してみました。しかし、私が望むように働いていない。特定のグループにユーザーを割り当てる方法を教えてください。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
私はグループの割り当てと管理のためにemailusermanagerでいくつかのパーミッションを作成しますか?もしそうなら、私は何をすべきですか? – vanam
お返事ありがとうございます。では、ユーザー登録プロセスの直後に作成したグループにユーザーを追加するにはどうすればよいですか? – vanam
私はdjangoを初めて使っています。私のコードでg = Group.objects.get(name = LABEL_NAME) g.user_set.add(YOUR_USER)を追加した後でも、登録ユーザーを特定のグループに割り当てることができませんでした。どうすれば解決できますか? – vanam