Search code examples
djangodjango-testing

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?


Solution

  • The test client has a login method.

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