I am trying to test a User model and view in a Python 3.4 environment, but I am having difficulties resolving an issue.
In my app, only staff users should be able to add/delete/modify a user profile. Hence, on setUp I create an admin user with the field is_staff set. Then, in the test case I force authentication as this admin user, which should allow me to create a new user. This code is shown below:
class UserTests(APITestCase):
def setUp(self):
self.admin = User(username='admin', password='pass', is_staff=True)
self.admin.save()
def test_create_user(self):
"""
Ensure we can create a new user object without any optional fields.
"""
url = reverse('user-list')
data = {'username': 'adam', 'is_staff': False}
self.client.force_authenticate(user='admin')
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data, data)
Running this test case results in the follow error trace:
Error
Traceback (most recent call last):
File "/Users/Jonathan/GitHub/h2oiq_api/h2oiq_api/test.py", line 19, in test_create_user
response = self.client.post(url, data, format='json')
.
.
.
File "/Users/Jonathan/.virtualenvs/h2oiq-api/lib/python3.4/site-packages/rest_framework/test.py", line 90, in post
return self.generic('POST', path, data, content_type, **extra)
File "/Users/Jonathan/.virtualenvs/h2oiq-api/lib/python3.4/site-packages/rest_framework/views.py", line 359, in initial
self.check_permissions(request)
.
.
.
File "/Users/Jonathan/.virtualenvs/h2oiq-api/lib/python3.4/site-packages/rest_framework/views.py", line 304, in check_permissions
if not permission.has_permission(request, self):
File "/Users/Jonathan/.virtualenvs/h2oiq-api/lib/python3.4/site-packages/rest_framework/permissions.py", line 55, in has_permission
return request.user and request.user.is_staff
AttributeError: 'str' object has no attribute 'is_staff'
Could someone please elaborate on why this attribute is missing? I have read the Django REST framework documentation thoroughly, especially the APIClient, Permissions, and BasicAuthentication guides, but I have not been able to find any additional info on this issue. I have tried commenting out the forced authentication, and that did not fix anything.
Any amount of help or insight is appreciated! I am learning Django REST as I go.
force_authenticate()should be getting a user object, not the string of the username. Soself.client.force_authenticate(user=self.admin)in your case.