Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11523

Django test Client simulate logged in user

I am new to Django test Client. I want to test a view that uses @login_required . I was wondering if I can do that using the simple Client() like this:

>>> from django.test import Client
>>> c = Client()
>>> r = c.get("/libros/nuevo_libro/perfil/farseer/")

But, of course, the response is always a 302:

>>> r.status_code
302

Cause the @login_required decorator redirects it to the login page.

Is it possible to simulate in this kind of tests that the user is logged in?

Upvotes: 2

Views: 1457

Answers (1)

Alasdair
Alasdair

Reputation: 308769

The test client has a login method.

c = Client()
c.login(username='fred', password='secret')
response = c.get("/libros/nuevo_libro/perfil/farseer/")

Upvotes: 6

Related Questions