Django Register Form 'AnonymousUser' object has no attribute 'backend'

后端 未结 2 1633
悲哀的现实
悲哀的现实 2020-12-18 09:48

I have the following register view that enters a new user. I want it to enter the new user and then log in automatically. It saves through the User record but returns this e

相关标签:
2条回答
  • 2020-12-18 09:59

    I had the same error for a newly registering user and it left me frustrated for an hour.

    There was a piece of code that tried to log user in right after the registration.
    Usually it worked just fine, but not this time.

    def attempt_login(self, email, password):
        user = authenticate(username=email, password=password)
        login(self.request, user)
    
        return user 
    

    It seemed that authenticate returned None, and then calling login with None caused this exception. But I was sure the User has been created after registration.

    Finally, I realized that this particular user's login was longer than 30 characters, and the form field had no validation. The login would get truncated in the database, and therefore authenticate was called for non-existent login.

    0 讨论(0)
  • 2020-12-18 10:03

    Your user will never authenticate, because you're saving the password in plain text - and authenticate expects a hashed password. You should call user.set_password(password) on the newly-created user object before saving it to the db - see the built-in UserCreationForm.

    0 讨论(0)
提交回复
热议问题