Search code examples
pythondjangodjango-testingdjango-tests

The Django test client redirects to the login page with a logged-in superuser


The Problem

I am trying to connect a superuser to the Django test client, and then access a page in the Django administration interface with a GET method. However, I get a redirect to the login page, even though the superuser is properly logged in.

The Code

def test(self) -> None:
    client = Client()
    user = User.objects.create(username='user', is_superuser=True)
    client.force_login(user)
    response = client.get(f'/admin/management/establishment/', follow=True)

    print("Redirect chain\t", response.redirect_chain)
    print("Request user\t", response.wsgi_request.user)
    print("Is superuser\t", response.wsgi_request.user.is_superuser)

The Output

Redirect chain   [('/admin/login/?next=/admin/management/establishment/', 302)]
Request user     user
Is superuser     True

Additional Information

  • Same result with a user having a password and an email
  • Tested on a new Django project

The Question

Do you know why I have this redirection and how I can avoid it?


Solution

  • Problem source

    It seems that setting a user as superuser with is_superuser=True does not allow them to access the Django admin interface.

    Only staffs can log in, so the is_staff=True attribute must be added to the user creation.

    It's surprising that superusers are not considered staff by default.

    Solution

    Creating the user with the following line does not redirect to the login page:

    user = User.objects.create(username='user', is_superuser=True, is_staff=True)