Django force_login not logging the Django Client in?

Viewed 3203

I must be missing something obvious here but I can't see it so maybe you can help ?

I'm using Pytest to test a Django form and it's creation of an object. I'm using Django Client object and trying to force_login which according to the result is not working since in the response url contains a redirect to the login page as if the user would not be logged in...

Why is this happening, what am I doing wrong and how to fix it?

Here's the code:

from django.test import TestCase, RequestFactory, Client

class TestViews(TestCase):

@classmethod
def setUpClass(cls):
    super(TestViews, cls).setUpClass()
    cls.user = mixer.blend(get_user_model())
    cls.patient = mixer.blend('patient.Patient', created_by=cls.user)
    cls.factory = RequestFactory()


@pytest.mark.django_db
def test_patient_creation_form_valid(self):
    c = Client()
    c.force_login(self.user)
    response = c.post(reverse('NewPatientForm'), {
        'name': 'John',
        'surname': 'Smith',
        'phone': '601123456',
        'email': 'john.smith@gmail.com',
    })
    self.assertEqual(response.status_code, 302)
    np = c.get(response.url)

Thanks!

1 Answers

I was having a similar issue in my tests where the user was getting redirected to the login page even though I was using force_login.

In fact, the user was logged in, but was missing a permission required to view the page.

When I added the required permission (as follows), I was able to post successfully to the page without being redirected.

    perm = Permission.objects.get(codename='can_approve_requests')
    user.user_permissions.add(perm)

More info on permission here Django Permissions and Authorization

I hope this helps.

Related