Django Manager isn't available; 'auth.User' has been swapped for 'users.MyUser'

孤人 提交于 2020-03-03 03:06:48

问题


I created Custom UserModel in Django 1.11 and I need a function which allows users to sign in I think my custom user model is incompatible with my function How can I fix?

see error message in the image below :

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})

I set it settings.py AUTH_USER_MODEL = 'users.MyUSer'


回答1:


You have created custom user. Add this in models.py, views.py, forms.py-

from django.contrib.auth import get_user_model
User = get_user_model()


来源:https://stackoverflow.com/questions/47193902/django-manager-isnt-available-auth-user-has-been-swapped-for-users-myuser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!