[Fixed]-Django how to set request user in client test

16๐Ÿ‘

I was trying to do the same myself but found out that Django Test Client does not set the user in the request and it is not possible to set request.user while using Client any other way. I used RequestFactory to that.

def setUp(self):
    self.request_factory = RequestFactory()
    self.user = User.objects.create_user(
        username='javed', email='javed@javed.com', password='my_secret')
    
def test_my_test_method(self):
    payload = {
        'question_title_name': 'my first question title',
        'question_name': 'my first question',
        'question_tag_name': 'first, question'
    }
    request = self.request_factory.post(reverse('home'), payload)
    request.user = self.user
    response = home_page(request)

More about request factory here

๐Ÿ‘คJaved

12๐Ÿ‘

Try this:

from django.test import TestCase, Client

from django.contrib.auth.models import User

class YourTestCase(TestCase):
    def test_profile(self, user_id):
        user = User.objects.create(username='testuser')
        user.set_password('12345')
        user.save()
        client = Client()
        client.login(username='testuser', password='12345')
        response = client.get("/account/profile/{}/".format(user.id), follow=True)
        self.assertEqual(response.status_code, 200)

Here, I first create the user and set the login credentials for the user. Then I create a client and login with that user. So in your views.py, when you do request.user, you will get this user.

๐Ÿ‘คSarin Madarasmi

2๐Ÿ‘

This works:

self.client.force_authenticate(user=user)
๐Ÿ‘คSteig

2๐Ÿ‘

If you use django.test you can do something like that:

self.client.force_login(user)
๐Ÿ‘คDainius

0๐Ÿ‘

If you have a response, you can access response.context['user'].

If you need a response object, just call any view that will create a context, e.g. response = self.client.get('/').

๐Ÿ‘คarcanemachine

Leave a comment