如何修复“管理器不可用; 'auth.User'已被交换'

时间:2019-06-22 14:29:12

标签: django django-models python-3.7

我正在设置一个CustomUser,以使用电子邮件作为用户名(消除用户名)。这是我一直遵循的指南。 https://wsvincent.com/django-referencing-the-user-model/

我一直在尝试使用包含设置中的AUTH_USER_MODEL ='core_app.CustomUser'的get_user_model。当我尝试使用registrationcompany函数进行注册时,出现错误。

settings.py

AUTH_USER_MODEL = 'core_app.CustomUser'
INSTALLED_APPS = [
    'accounts',
    'core_app.apps.CoreAppConfig',
]

core_app / models.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import gettext_lazy as _

from .managers import CustomUserManager


class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True, null=True)

    USERNAME_FIELD = 'email'
    objects = CustomUserManager()

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

core_app / managers.py

from django.contrib.auth.models import BaseUserManager


class CustomUserManager(BaseUserManager):
    def create_user(self, email, password=None, **kwargs):
        if not email:
            raise ValueError('Email field is required')

        email = self.normalize_email(email)
        user = self.model(email=email, **kwargs)
        user.set_password(password)
        user.save()
        return user

accounts / views.py

def registercompany(request):
    if request.method =='POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            new_user = form.save()
            new_user = authenticate(username=form.cleaned_data['username'],
                                    password=form.cleaned_data['password1'],
                                    )
            login(request, new_user)
            return redirect(reverse('nonprofits:filterview'))
    else:
        form = RegistrationForm()

        args = {'form': form}
        return render(request, 'accounts/reg_form_company.html', args)

accounts / models.py

from django.db import models
from django.contrib.auth import get_user_model

class UserProfile(models.Model):
    user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
    organisation_name = models.CharField(blank=True, default='',
    objects = models.Manager()

    def __str__(self):
        return self.user.username


def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = UserProfile.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=get_user_model())

accounts / forms.py

...
from django.contrib.auth import get_user_model
from .models import UserProfile
from core_app.models import CustomUser
...


class RegistrationForm(UserCreationForm):

    email = forms.EmailField(required=True)

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']

        if commit:
            user.save()
        if commit:
            user = super(RegistrationForm, self).save(commit=False)
            user.userprofile.save()

        return user

这是我要帮助解决的错误。

追踪

AttributeError at /account/register/company
Manager isn't available; 'auth.User' has been swapped for 'core_app.CustomUser'
Request Method: POST
Request URL:    http://127.0.0.1:8000/account/register/company
Django Version: 2.2.2
Exception Type: AttributeError
Exception Value:    
Manager isn't available; 'auth.User' has been swapped for 'core_app.CustomUser'
Exception Location: /.../venv/lib/python3.7/site-packages/django/db/models/manager.py in __get__, line 188

/.../accounts/views.py in registercompany
        if form.is_valid(): …
▼ Local vars
Variable    Value
form    
<RegistrationForm bound=True, valid=False, fields=(username;password1;password2;email;account_type;organisation_name)>
request 
<WSGIRequest: POST '/account/register/company'>

0 个答案:

没有答案