Django Manager不可用; “auth.User”已被替换为“users.MyUser”

时间:2017-11-09 04:27:36

标签: python django django-models django-users

我在Django 1.11中创建了Custom UserModel,我需要一个允许用户登录的功能 我认为我的自定义用户模型与我的功能不兼容 我该如何解决?

请参阅下图中的错误消息:

enter image description here

users.models.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from apps.teams.models import Team
import uuid

class MyUserManager(BaseUserManager):
    def _create_user(self, username, password, **extra_kwargs):
        user = self.model(username=username, **extra_kwargs)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password, **extra_kwargs):
        extra_kwargs.setdefault('is_active', True)
        extra_kwargs.setdefault('is_superuser', True)
        extra_kwargs.setdefault('is_staff', True)

        if extra_kwargs.get('is_superuser', None) is not True:
            raise ValueError('관리자 권한이 필요합니다.')

        return self._create_user(username, password, **extra_kwargs)

class MyUser(AbstractBaseUser):
    """
    유저 모델
    """
    POSITION_TYPES = (
        ('a', '대표'),
        ('b', '팀장'),
        ('c', '과장'),
        ('d', '대리'),
        ('e', '주임'),
        ('f', '사원'),
        ('g', '인턴'),
    )
    uid = models.UUIDField(
        primary_key=True,
        editable=False,
        default=uuid.uuid4,
        verbose_name='팀 고유 아이디'
    )
    username = models.CharField(
        max_length=20,
        unique=True,
        verbose_name='아이디'
    )
    name = models.CharField(
        max_length=10,
        verbose_name='이름'
    )
    email = models.EmailField(
        verbose_name='이메일'
    )
    team = models.ForeignKey(
        Team,
        verbose_name='소속',
        null=True,
        blank=True
    )
    position = models.CharField(
        max_length=2,
        choices=POSITION_TYPES,
        default='g',
        verbose_name='직급'
    )
    birth = models.DateField(
        null=True,
        blank=True,
        verbose_name='생일'
    )
    date_joined = models.DateField(
        null=True,
        blank=True,
        verbose_name='입사일'
    )
    date_exited = models.DateField(
        null=True,
        blank=True,
        verbose_name='퇴사일'
    )
    is_superuser = models.BooleanField(
        default=False,
        verbose_name='관리자 여부'
    )
    is_staff = models.BooleanField(
        default=False,
        verbose_name='스태브 여부'
    )
    is_active = models.BooleanField(
        default=False,
        verbose_name='활성화 여부'
    )

    objects = MyUserManager()

    USERNAME_FIELD = 'username'


    class Meta:
        db_table = 'users'

    def __str__(self):
        return self.username

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, module):
        return True

users.forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from .models import MyUser
from apps.teams.models import Team


class SignupFrom(UserCreationForm):
    POSITION_TYPES = (
        ('a', '대표'),
        ('b', '팀장'),
        ('c', '과장'),
        ('d', '대리'),
        ('e', '주임'),
        ('f', '사원'),
        ('g', '인턴'),
    )

    username = forms.CharField(
        required=True,
        label="아이디",
        widget=forms.TextInput(
            attrs={
                'class':'form-control',
                'placeholder': '아이디',
                'required' : 'True',
            }
        )
    )

    password1 = forms.CharField(
        required=True,
        label="패스워드",
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control',
                'placeholder': '패스워드',
                'required' : 'True'
            }
        )
    )

    password2 = forms.CharField(
        required=True,
        label="패스워드 확인",
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control',
                'placeholder': '패스워드 확인',
                'required': 'True'
            }
        )
    )

    name = forms.CharField(
        required=True,
        label="이름",
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': '아이디',
                'required': 'True',
            }
        )
    )
    email = forms.EmailField(

        required=False,
        label="이메일",
        widget=forms.EmailInput(
            attrs={
                'class': 'form-control',
                'placeholder': '이메일',
                'required': 'True',
            }
        )
    )
    team = forms.ModelChoiceField(
        required=True,
        label="소속",
        queryset=Team.objects.all(),
        widget=forms.Select(
            attrs={
                'class': 'form-control',
            }
        )
    )

    position = forms.ChoiceField(
        required=False,
        label="직급",
        choices=POSITION_TYPES,
        widget=forms.Select(
            attrs={
                'class': 'form-control',
                'required' : 'True',
            }
        )

    )
    birth = forms.DateField(
        label="생일",
        widget=forms.DateInput(
            attrs={
                'class': 'form-control',
                'required': 'True',
            }
        )
    )
    date_joined = forms.DateField(
        required=True,
        label="입사일",
        widget=forms.DateInput(
            attrs={
                'class': 'form-control',
                'required': 'True',
            }
        )
    )

    class Meata:
        model = MyUser
        fields = ("username", "name", "password1", "password2", "team", "position", "email", "birth", "date_joined")


class LoginForm(AuthenticationForm):
    username = forms.CharField(
        max_length=10,
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'placeholder': '아이디',
                'required': 'True',
            }
        )
    )
    password = forms.CharField(
        widget=forms.PasswordInput(
            attrs={
                'class': 'form-control',
                'placeholder': '패스워드',
                'required': 'True',
            }
        )
    )

users.views.py

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from .forms import SignupFrom


def signup(request):
    signupform = SignupFrom()
    if request.method == 'POST':
        signupform = SignupFrom(request.POST)
        if signupform.is_valid():
            user = signupform.save(commit=False)
            user.save()
            return HttpResponseRedirect(
                reverse("sign_ok")
            )
    return render(request, "registration/signup.html", {"signupform": signupform})

我设置了settings.py AUTH_USER_MODEL ='users.MyUSer'

1 个答案:

答案 0 :(得分:2)

您已创建自定义用户。在models.py,views.py,forms.py -

中添加它
from django.contrib.auth import get_user_model
User = get_user_model()