hohel hohel - 4 months ago 9
Python Question

Get to self.request.user in test python

I want to make tests for app, and I just can't make it right.
I have such function:

def get_queryset(self):
return User.objects.filter(id=self.request.user.id)

And I wrote such test:

def test_Uzytkownik_get_query(self):
self.c = Client()
self.user = User.objects.create_user(username='john', email='lennon@thebeatles.com', password='johnpassword')
self.c.login(username='john', password='johnpassword')
response = self.c.get('/')

But I get this

AttributeError: 'User' object has no attribute 'request'

I know that john isn't actually result of this queryset, but i can't do any test because of this: self.request.user.whatever.


Sorry guys I didn't give this information. I'm using Django, and class in which is this function looks like this:

class UzytkownikViewSet(viewsets.ModelViewSet):
def get_queryset(self): return


You're calling get_queryset on your view class, not in an instance. But since it is an instance method, it expects the instance as the first parameter, self. So it takes what you have actually passed as the first parameter, the user, and assigns that to self instead, hence the error.

Your approach to this test is wrong. Rather than call get_queryset directly, you should be using the functionality of the test client which allows you to inspect the template context used to render the response:

self.assertEqual(response.context['user'].username, 'john')