mardi 11 février 2020

Django - Cannot test request as authenticated user with django-allauth

I have a new django project (2.2), a custom user model and django-allauth to manage user registration (not via social, just with the email confirmation) and I'm trying to test some protected views.

In the setUp method of the test I create a new user and create a new EmailAddress (from allauth.account.models) with verified and primary set to True.

Next I try to login with: self.client.login(username=username, password=password) and I get True so everything is working so far and the user is logged.

Now if I try to get any views that requires login I always get a 301 redirect to the login page!

I looked around but didn't find a solution to my problem so far.

Let me show you some code:

user creation in setUp

username = 'test@test.com'
password = 'testtesttest'

new_user = User.objects.create_user(
    username=username,
    email=username,
    password=password,
    )
new_user.save()
new_user.is_active = True
new_user.save()

new_email_address = EmailAddress(
    user_id=new_user.id,
    email=username,
    verified=True,
    primary=True,
    )
new_email_address.save()

login and test logged in

logged_in = self.client.login(email=username, password=password)
self.assertTrue(logged_in)  # and this works as expected

Now if I try to request a view that requires login:

response = self.client.get("/protected")

I get <HttpResponsePermanentRedirect status_code=301, "text/html; charset=utf-8", url="/protected/">

What am I doin't wrong?

Thanks in advance for the help.

(this is my first question...I hope I've explained clearly my problem. Let me know if you need more info)

Aucun commentaire:

Enregistrer un commentaire