经理不在; 'auth.User'已被换为'polls.User'

时间:2018-02-16 09:25:10

标签: python django

我创建了一个不同版本的User模型,其中没有用户名字段,我现在正在尝试实现登录功能,但我一直收到错误

Manager isn't available; 'auth.User' has been swapped for 'polls.User'

我搜索了本网站的其余部分并试图在下方实施该功能以解决问题,但无济于事。

from django.contrib.auth import get_user_model

User = get_user_model()

这是我的其余文件

浏览

    from django.http import HttpResponse
    from django.shortcuts import get_object_or_404, render, render_to_response, redirect
    from django.contrib.auth.decorators import login_required
    from django.contrib.auth import login, authenticate
    from django.shortcuts import render, redirect

    from polls.forms import SignUpForm
    from django.contrib.auth import get_user_model

    User = get_user_model()

    @login_required
    def home(request):
        return render(request, 'home.html')

    def signup(request):
        if request.method == 'POST':
            form = SignUpForm(request.POST)
            if form.is_valid():
                form.save()
                username = None
                raw_password = form.cleaned_data.get('password1')
                user = authenticate(password=raw_password)
                login(request, user)
                return redirect('home')
        else:
            form = SignUpForm()
        return render(request, 'signup.html', {'form': form})

形式

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User


class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')
    username = None

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'password1', 'password2', )

模型

from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models
from django.utils.translation import ugettext_lazy as _

class UserManager(BaseUserManager):
    """Define a model manager for User model with no username field."""

    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """Create and save a User with the given email and password."""
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **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 a regular User with the given email and password."""
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        """Create and save a SuperUser with the given email and password."""
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

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


class User(AbstractUser):
    """User model."""

    username = None
    email = models.EmailField(_('email address'), unique=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

如果有人能提供任何明确的信息,我们将不胜感激

3 个答案:

答案 0 :(得分:12)

forms.py 中,您还必须更改

from django.contrib.auth.models import User

from django.contrib.auth import get_user_model

User = get_user_model()

这适用于您使用User的任何地方。错误的回溯将告诉您错误的确切位置。在寻求帮助调试时,请始终在问题中包含回溯。

答案 1 :(得分:1)

编辑: 没关系,看看HåkenLid的回答。我误解了这个问题。

但是,你必须修改下面的代码

取决于您使用的Django版本,但问题出在这一行:

user = authenticate(password=raw_password)

您还应传递用户名:

user = authenticate(username='john', password='secret')

然后,authenticate方法将返回User个实例或None

if user is not None:
    login(request, user)
else:
    # authenticated failed

答案 2 :(得分:0)

看看这里已经被别人解决了。 [stackoverflow上的解决方案Link