Reputation: 13
I have a new Django project (version 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.
If I try to view anything that requires login, I get a 301 redirect to the login page.
Here's my code:
user creation in setUp
username = '[email protected]'
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 missing or doing wrong?
Upvotes: 1
Views: 466
Reputation: 20702
The redirect you're showing actually shows you the url it's redirecting to: url="/protected/"
. So you're not redirected to the login page.
Note that a normal redirect would be 302 redirect (temporary), whereas here you see a permanent redirect, 301.
Either request the correct url (self.client.get('/protected/')
) or follow through the redirects: self.client.get('/protected', follow=True)
. That way your response will be for the final page and you can test whether its contents are what you expect.
Upvotes: 1