I have a view that is changing a field of request.user
:
def test(request):
request.user.is_provider = False
request.user.save()
print(request.user.is_provider)
return HttpResponse(status=200)
Now I am testing the function and I have the following test:
class RoleSwitchTests(TestCase):
def test_switch_to_customer(self):
User = get_user_model()
user = User.objects.create_user(
username='test',
email='test',
password='test',
first_name='test',
last_name='test',
is_provider=True,
is_admin=False,
)
self.client.login(username='test', password='test')
response = self.client.post('/test/', follow=True)
print(user.is_provider)
self.assertEqual(response.status_code, 200)
self.assertFalse(user.is_provider)
self.assertFalse(user.is_provider)
fails here. For some reason, request.user.is_provider
is False
in test
, but in test_switch_to_customer
, user.is_provider
is True
. I know these refer to the same user because they have the same id
, so why is the modification not being preserved here?
You should use refresh_from_db to reload the updated user from the database after the post
user.refresh_from_db()