'AnonymousUser' 对象没有属性 'backend' 自定义用户

'AnonymousUser' object has no attribute 'backend' customuser

我正在使用 Django 1.7 python 3.4 我创建了一个派生自 AbstractBaseUser 的自定义 MyUser class。现在,当我尝试注册用户时,出现错误 'AnonymousUser' object has no attribute 'backend'。 views.py

def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if not form.is_valid():
            return "form invalid"  # render(request, 'auth/signup.html', {'form': form})
        else:

            email = form.cleaned_data.get('email')
            enterprise = form.cleaned_data.get('enterprise')
            first_name = form.cleaned_data.get('first_name')
            last_name = form.cleaned_data.get('last_name')
            password = form.cleaned_data.get('password')
            MyUser.objects.create_myuser(email=email, enterprise=enterprise, first_name=first_name, last_name=last_name,
                                         password=password,)
            myuser = authenticate(email=email, password=password)
            # myuser.backend = 'django.contrib.auth.backends.ModelBackend'
            # authenticate(email=email, password=password)
            login(request, myuser)
            welcome_post = u'{0}from {1} has joined the network.'.format(myuser.first_name, myuser.enterprise)
            node = Node(myuser=myuser, post=welcome_post)
            node.save()
            return redirect('/')
    else:
        return render(request, 'accounts/signup.html', {'form': SignupForm()})

另外,用户没有被保存到数据库中。

Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\sp\ilog_dev\accounts\views.py" in signup
  27.             login(request, myuser)
File "C:\Python34\lib\site-packages\django\contrib\auth\__init__.py" in login
  98.     request.session[BACKEND_SESSION_KEY] = user.backend
File "C:\Python34\lib\site-packages\django\utils\functional.py" in inner
  225.         return func(self._wrapped, *args)

Exception Type: AttributeError at /accounts/signup/
Exception Value: 'AnonymousUser' object has no attribute 'backend'

models.py

class MyUserManager(BaseUserManager):
    def create_myuser(self, email, first_name, last_name, enterprise, password=None):
        if not email:
            raise ValueError('Users must have an email address')
        if not first_name:
            raise ValueError("must have a first_name")
        if enterprise not in Enterprise.objects.all():
            raise ValueError("please specify a valid enterprise or register a new one")

        myuser = self.model(email=self.normalize_email(email), first_name=first_name,
                            last_name=last_name, enterprise=enterprise,)

        myuser.set_password(password)
        myuser.save()  # using=self._db
        print("user saved")

        return myuser

这里的问题是您将身份验证模型迁移到数据库,然后作为第二步迁移了您的自定义用户。

您需要从一个干净的数据库开始,并在您向数据库发出的第一个迁移命令中迁移您的自定义用户。

documentation 中提到您应该始终将创建自定义用户表作为第一步,否则 django 会陷入困境。

Warning

Changing AUTH_USER_MODEL has a big effect on your database structure. It changes the tables that are available, and it will affect the construction of foreign keys and many-to-many relationships. If you intend to set AUTH_USER_MODEL, you should set it before creating any migrations or running manage.py migrate for the first time.

Changing this setting after you have tables created is not supported by makemigrations and will result in you having to manually fix your schema, port your data from the old user table, and possibly manually reapply some migrations.

问题很简单。用户未保存到数据库中。正如您所说,您的用户模型中的 save 方法一定有问题。此外,save 方法没有阻止它的错误,但它作为一段代码工作正常,除了保存对象

因此,当您注册为用户时,一切运行正常,但用户未保存。之后它会尝试回叫用户和它 returns 匿名用户。现在,当您调用用户的任何属性时,都会引发类似的错误。

检查你的保存方法。