AUTH_USER_MODEL引用尚未安装和创建的模型..不能登录的AbstractUser模型

时间:2022-07-25 19:22:45

AUTH_USER_MODEL error solved in EDIT3. Passwords still will not save on user creation via form.

在EDIT3中解决了AUTH_USER_MODEL错误。密码仍然无法通过表单保存用户创建。

I'm using Django 1.5 playing around with the new user override/extension features, and I am not able to register new users via my registration form - only via the Admin. When registering via the registration form, I get the following error:

我正在使用Django 1.5使用新的用户覆盖/扩展功能,我无法通过我的注册表单注册新用户 - 只能通过管理员。通过注册表注册时,我收到以下错误:

Manager isn't available; User has been swapped for 'poker.PokerUser'

经理不在;用户已被换为'poker.PokerUser'

models.py:

models.py:

class PokerUser(AbstractUser):
    poker_relate = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
    token = models.EmailField()
    USER_CHOICES = (
        ('1', 'Staker'),
        ('2', 'Horse')
    )
    user_type = models.CharField(choices=USER_CHOICES, max_length=10)
    username1 = models.CharField(null=True, blank=True, max_length=40)
    username2 = models.CharField(null=True, blank=True, max_length=40)
    username3 = models.CharField(null=True, blank=True, max_length=40)
    username4 = models.CharField(null=True, blank=True, max_length=40)
    username5 = models.CharField(null=True, blank=True, max_length=40)

PokerUserForm model:

PokerUserForm模型:

class PokerUserForm(UserCreationForm):
    class Meta:
        model = PokerUser
        fields = ('username','password1','password2','email','user_type','token','username1','username2','username3','username4','username5',)

I've attempted to change the model in the PokerUserForm model to use get_user_model() instead of explicitly defining the model by setting model = get_user_model() instead of model = PokerUser but then I receive the following error:

我试图通过设置model = get_user_model()而不是model = PokerUser来改变PokerUserForm模型中的模型以使用get_user_model()而不是显式定义模型,但后来我收到以下错误:

django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'poker.PokerUser' that has not been installed

My AUTH_USER_MODEL is setup in my settings.py like so:

我的settings.py中设置了我的AUTH_USER_MODEL,如下所示:

AUTH_USER_MODEL = 'poker.PokerUser'

AUTH_USER_MODEL ='poker.PokerUser'

On we go - my Registration view in views.py:

我们去 - 我在views.py中的注册视图:

def UserRegistration(request):
    player = PokerUser()

    if request.method == 'POST':
        form = PokerUserForm(request.POST, instance=player)
        if form.is_valid():
            player.email_address = form.cleaned_data['email']
            player.user_type = form.cleaned_data['user_type']
            # if player is staker, token is their own email. otherwise their token is their staker's email and
            # their relation is their staker
            if player.user_type == '1' or player.user_type == 'staker':
                player.token = player.email_address
            else:
                player.token = form.cleaned_data['token']
                staker = PokerUser.objects.get(email=player.token)
                player.poker_relate = staker
            player.save()
            return HttpResponseRedirect('/')
    else:
        form = PokerUserForm()
    initialData = {'form': form}
    csrfContext = RequestContext(request, initialData)
    return render_to_response('registration/register.html', csrfContext)

EDIT1:

EDIT1:

According to the docs, the UserCreationForm must be recreated for use with custom user classes.

根据文档,必须重新创建UserCreationForm以用于自定义用户类。

I overrode the entire UserCreationForm as follows:

我重写了整个UserCreationForm,如下所示:

class UserCreationForm(forms.ModelForm):
    """
    A form that creates a user, with no privileges, from the given username and
    password.
    """
    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
        'password_mismatch': _("The two password fields didn't match."),
        }
    username = forms.RegexField(label=_("Username"), max_length=30,
        regex=r'^[\w.@+-]+$',
        help_text=_("Required. 30 characters or fewer. Letters, digits and "
                    "@/./+/-/_ only."),
        error_messages={
            'invalid': _("This value may contain only letters, numbers and "
                         "@/./+/-/_ characters.")})
    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."))

    class Meta:
        model = PokerUser
        fields = ('username','password1','password2','email','user_type','token','username1','username2','username3','username4','username5',)

    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        try:
            PokerUser.objects.get(username=username)
        except PokerUser.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])

    def clean_password2(self):
        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'])
        return password2

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

And this was able to resolve this error:

这能够解决这个错误:

The Manager isn't available; User has been swapped for 'poker.PokerUser'

经理不在;用户已被换为'poker.PokerUser'

Now, the users get created but are not able to log in. When I check the users in the admin, all of the information seems to be correct except for the password. Adding a password manually in the admin does not seem to work correctly. Still, adding users via the admin work correctly.

现在,用户已创建但无法登录。当我检查管理员中的用户时,除密码外,所有信息似乎都是正确的。在管理员中手动添加密码似乎无法正常工作。仍然,通过管理员添加用户正常工作。

EDIT 2:

编辑2:

I'm still unable to login as any of my AbstractUser models created via the registration form. I have completely overridden the UserCreationForm as outlined above, and am unable to implement get_user_model() with this error:

我仍然无法登录通过注册表单创建的任何AbstractUser模型。我已完全覆盖了上面概述的UserCreationForm,并且无法使用此错误实现get_user_model():

AUTH_USER_MODEL refers to model 'poker.PokerUser' that has not been installed

AUTH_USER_MODEL指的是尚未安装的模型'poker.PokerUser'

The Django code for get_user_model() is:

get_user_model()的Django代码是:

 def get_user_model():
    "Return the User model that is active in this project"
    from django.conf import settings
    from django.db.models import get_model

    try:
        app_label, model_name = settings.AUTH_USER_MODEL.split('.')
    except ValueError:
        raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
    user_model = get_model(app_label, model_name)
    if user_model is None:
        raise ImproperlyConfigured("AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL)
    return user_model

Since I have AUTH_USER_MODEL = 'poker.PokerUser' setup in my settings.py, this should work. I've verified this through the Django console:

由于我在settings.py中设置了AUTH_USER_MODEL ='poker.PokerUser',这应该可行。我通过Django控制台验证了这一点:

>>> from django.contrib.auth import get_user_model
>>> settings.AUTH_USER_MODEL
Out[14]: 'poker.PokerUser'
>>> from django.db.models import get_model
>>> app_label, model_name = settings.AUTH_USER_MODEL.split('.')
>>> user_model = get_model(app_label, model_name)
>>> user_model
Out[18]: poker.models.PokerUser

However the implementation still does not work correctly.

但是,实现仍然无法正常工作。

If you've read this far, thanks!

如果您已经读过这篇文章了,谢谢!

EDIT3:

EDIT3:

AUTH_USER_MODEL refers to model 'poker.PokerUser' that has not been installed has been fixed. I accidentally had the UserCreationForm that I recreated in poker.models instead of registration.forms, so when I ran get_user_model() that was assigned to poker.PokerUser, it couldn't resolve since it was already in that location.

AUTH_USER_MODEL引用尚未安装的模型'poker.PokerUser'已修复。我不小心得到了我在poker.models而不是registration.forms中重新创建的UserCreationForm,所以当我运行分配给poker.PokerUser的get_user_model()时,它无法解析,因为它已经在那个位置。

Now the only issue left is that when creating new users, their passwords will not save. I've narrowed it down to a single method in the UserCreationForm by placing print statements here:

现在唯一的问题是,在创建新用户时,他们的密码将无法保存。通过在此处放置print语句,我将其缩小为UserCreationForm中的单个方法:

def clean_password2(self):
    password1 = self.cleaned_data.get("password1")
    print password1
    password2 = self.cleaned_data.get("password2")
    print password2
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError(
            self.error_messages['password_mismatch'])
    print password2
    return password2

def save(self, commit=True):
    user = super(UserCreationForm, self).save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    print self.cleaned_data["password1"]
    if commit:
        user.save()
    return user

The print password1 and print password1 statements in clean_password2 display the plain text password, but print self.cleaned_data["password1"] in the save method is blank. Why is my form data not being passed to the save method?

clean_password2中的print password1和print password1语句显示纯文本密码,但save方法中的print self.cleaned_data [“password1”]为空白。为什么我的表单数据没有传递给save方法?

TL;DR AbstractUser model creation is working in both Admin and via registration form, but only the users created via Admin are able to login. The users created via the registration form are unable to log in and seem to be saved without a password - all other information is saved correctly.

TL; DR AbstractUser模型创建在Admin和via注册表单中都有效,但只有通过Admin创建的用户才能登录。通过注册表单创建的用户无法登录并且似乎在没有密码的情况下保存 - 所有其他信息都已正确保存。

4 个解决方案

#1


11  

Ok there were three issues here for me, so I'm going to address all of them since I am pretty sure the first two will come up for someone else.

好的,这里有三个问题,所以我要解决所有问题,因为我很确定前两个会出现给别人。

  • Manager isn't available; User has been swapped for 'poker.PokerUser'
  • 经理不在;用户已被换为'poker.PokerUser'

This was due to using but not recreating the UserCreationForm. When using custom models in 1.5, some model forms are available out of the box but this one must be recreated. See here for the docs.

这是由于使用但未重新创建UserCreationForm。在1.5中使用自定义模型时,一些模型表单可以开箱即用,但必须重新创建。请参阅此处了解文档。

  • The Manager isn't available; User has been swapped for 'poker.PokerUser'
  • 经理不在;用户已被换为'poker.PokerUser'

While I had AUTH_USER_MODEL = 'poker.PokerUser' set in my settings.py, I was calling get_user_model() from the poker.models location. You must call get_user_model() from a different location. Moving my form to registration.forms and calling get_user_model() from there worked correctly.

虽然我在settings.py中设置了AUTH_USER_MODEL ='poker.PokerUser',但我从poker.models位置调用了get_user_model()。您必须从其他位置调用get_user_model()。将我的表单移动到registration.forms并从那里调用get_user_model()工作正常。

  • New users not saving
  • 新用户不保存

This was just a brain fart on my end. In my UserRegistration model I was manipulating various fields from the form. When I passed those fields back to UserCreationForm for the save() method, I was not passing the password fields with it. Woops!

这对我来说只是一个脑屁。在我的UserRegistration模型中,我正在操作表单中的各个字段。当我将这些字段传递回UserCreationForm以获取save()方法时,我没有传递密码字段。 Woops!

#2


7  

I've run into this a few times. It's always been an import issue. Suppose we have core/models.py that implements a custom user and imports a symbol from another file (say Else):

我已经碰到了几次。这一直是一个导入问题。假设我们有core / models.py实现自定义用户并从另一个文件中导入符号(比如Else):

from Something import Else

class CustomUser(AbstractBaseUser):
    pass

And then we have another file that uses CustomUser and also defines Else. Let's call this something/models.py:

然后我们有另一个使用CustomUser的文件,并且还定义了Else。我们称之为/ models.py:

from core.models import CustomUser

class Else(models.Model):
    pass

class AnotherClass(models.model):
    user = models.ForeignKey(CustomUser)

When core/models.py goes to import Else, it evaluates something/models.py and runs into the AnotherClass definition. AnotherClass uses CustomUser, but CustomUser hasn't been installed yet because we're in the process of creating it. So, it throws this error.

当core / models.py导入Else时,它会计算某些/ models.py并运行到AnotherClass定义中。 AnotherClass使用CustomUser,但还没有安装CustomUser,因为我们正在创建它。所以,它抛出了这个错误。

I've solved this problem by keeping my core/models.py standalone. It doesn't import much from my other apps.

我通过保持我的core / models.py独立来解决这个问题。它不会从我的其他应用程序导入太多。

#3


0  

In my case updating, proper app_label in meta solved this issue

在我的情况下更新,meta中适当的app_label解决了这个问题

class APPUser(AbstractUser):
   password = models.TextField(blank=True)

   class Meta:
     app_label = 'app_auth'
     db_table = "app_user"

#4


-5  

To quote the Django docs:

引用Django文档:

You will also need to register your custom User model with the admin. If your custom User model extends django.contrib.auth.models.AbstractUser, you can use Django's existing django.contrib.auth.admin.UserAdmin class.

您还需要向管理员注册自定义用户模型。如果您的自定义用户模型扩展了django.contrib.auth.models.AbstractUser,则可以使用Django现有的django.contrib.auth.admin.UserAdmin类。

Check the contents of your admin.py file and make sure that you registered your custom model with the admin system using the django.contrib.auth.admin.UserAdmin class.

检查admin.py文件的内容,并确保使用django.contrib.auth.admin.UserAdmin类向管理系统注册了自定义模型。

#1


11  

Ok there were three issues here for me, so I'm going to address all of them since I am pretty sure the first two will come up for someone else.

好的,这里有三个问题,所以我要解决所有问题,因为我很确定前两个会出现给别人。

  • Manager isn't available; User has been swapped for 'poker.PokerUser'
  • 经理不在;用户已被换为'poker.PokerUser'

This was due to using but not recreating the UserCreationForm. When using custom models in 1.5, some model forms are available out of the box but this one must be recreated. See here for the docs.

这是由于使用但未重新创建UserCreationForm。在1.5中使用自定义模型时,一些模型表单可以开箱即用,但必须重新创建。请参阅此处了解文档。

  • The Manager isn't available; User has been swapped for 'poker.PokerUser'
  • 经理不在;用户已被换为'poker.PokerUser'

While I had AUTH_USER_MODEL = 'poker.PokerUser' set in my settings.py, I was calling get_user_model() from the poker.models location. You must call get_user_model() from a different location. Moving my form to registration.forms and calling get_user_model() from there worked correctly.

虽然我在settings.py中设置了AUTH_USER_MODEL ='poker.PokerUser',但我从poker.models位置调用了get_user_model()。您必须从其他位置调用get_user_model()。将我的表单移动到registration.forms并从那里调用get_user_model()工作正常。

  • New users not saving
  • 新用户不保存

This was just a brain fart on my end. In my UserRegistration model I was manipulating various fields from the form. When I passed those fields back to UserCreationForm for the save() method, I was not passing the password fields with it. Woops!

这对我来说只是一个脑屁。在我的UserRegistration模型中,我正在操作表单中的各个字段。当我将这些字段传递回UserCreationForm以获取save()方法时,我没有传递密码字段。 Woops!

#2


7  

I've run into this a few times. It's always been an import issue. Suppose we have core/models.py that implements a custom user and imports a symbol from another file (say Else):

我已经碰到了几次。这一直是一个导入问题。假设我们有core / models.py实现自定义用户并从另一个文件中导入符号(比如Else):

from Something import Else

class CustomUser(AbstractBaseUser):
    pass

And then we have another file that uses CustomUser and also defines Else. Let's call this something/models.py:

然后我们有另一个使用CustomUser的文件,并且还定义了Else。我们称之为/ models.py:

from core.models import CustomUser

class Else(models.Model):
    pass

class AnotherClass(models.model):
    user = models.ForeignKey(CustomUser)

When core/models.py goes to import Else, it evaluates something/models.py and runs into the AnotherClass definition. AnotherClass uses CustomUser, but CustomUser hasn't been installed yet because we're in the process of creating it. So, it throws this error.

当core / models.py导入Else时,它会计算某些/ models.py并运行到AnotherClass定义中。 AnotherClass使用CustomUser,但还没有安装CustomUser,因为我们正在创建它。所以,它抛出了这个错误。

I've solved this problem by keeping my core/models.py standalone. It doesn't import much from my other apps.

我通过保持我的core / models.py独立来解决这个问题。它不会从我的其他应用程序导入太多。

#3


0  

In my case updating, proper app_label in meta solved this issue

在我的情况下更新,meta中适当的app_label解决了这个问题

class APPUser(AbstractUser):
   password = models.TextField(blank=True)

   class Meta:
     app_label = 'app_auth'
     db_table = "app_user"

#4


-5  

To quote the Django docs:

引用Django文档:

You will also need to register your custom User model with the admin. If your custom User model extends django.contrib.auth.models.AbstractUser, you can use Django's existing django.contrib.auth.admin.UserAdmin class.

您还需要向管理员注册自定义用户模型。如果您的自定义用户模型扩展了django.contrib.auth.models.AbstractUser,则可以使用Django现有的django.contrib.auth.admin.UserAdmin类。

Check the contents of your admin.py file and make sure that you registered your custom model with the admin system using the django.contrib.auth.admin.UserAdmin class.

检查admin.py文件的内容,并确保使用django.contrib.auth.admin.UserAdmin类向管理系统注册了自定义模型。