Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'AnonymousUser' object has no attribute 'backend'

Tags:

python

django

Using django-socialregistration, got following error:

'AnonymousUser' object has no attribute 'backend'

How,

  1. I click on facebook connect url.
  2. That took me Facebook and ask me to login. So I did, asked permission, I granted.
  3. After that it redirect me to my site. And ask to setup. I provide user and email address.
  4. Once I submit, got error like above:

Trace point:

path/to_file/socialregistration/views.py in post
128.      self.login(request, user)

Do anybody know, what's wrong?

like image 833
Elisa Avatar asked Nov 30 '11 04:11

Elisa


3 Answers

Oh man i used to get this error all the time, basically you are calling

self.login(request, user)

without calling

authenticate(username=user, password=pwd)

first

when you call authenticate, django sets the backend attribute on the user, noting which backend to use, see here for more details https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.authenticate

like image 81
Paulo Avatar answered Oct 18 '22 18:10

Paulo


I had the same error for a newly registering user.

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

    return user 

I checked into database and the User has been created after registration, but this error was still there.

I figured out - user's login ( email ) was longer than 30 characters, and the form field had no validation. The username would get truncated in the database, and therefore authenticate was called for non-existent login.

254 - character is the advised length of email field.

Solution: emailfield-max_length-r11092.patch

like image 1
flyankur Avatar answered Oct 18 '22 18:10

flyankur


I just got this error and found this post.. My solution was in the case was in the registration process. When the user was registering, my api and serializer wasn't hashing the password.. So in the api_view i had to manually hash the password like this..

    from django.contrib.auth.hashers import make_password

    # In the register api..
    @ensure_csrf_cookie
    @api_view(['POST'])
    def register_api(request):

        # Anywhere before the serializer
        request.DATA['password'] = make_password(request.DATA['password'])

        # Then the serializer
        serializer = RegisterSerializer(data=request.DATA)

        # ... etc.. Note that if you want to login after register you will have
        # to store the initial password is some buffer because.. authentication
        # the none hashed version.. then
             authenticate(username=request.DATA['username'], password=someBuffer)

Hope that helps someone..

like image 1
user2923813 Avatar answered Oct 18 '22 18:10

user2923813