Django / DjangoRestFramework - 单元测试不验证使用 ORM 创建的用户

Django / DjangoRestFramework - unittest not authenticating user created using ORM

这是我的测试:

class PageTests(APITestCase):
    def setUp(self):
        Location.objects.create(locationName = 'Location of Mine', LocationCode = 'LOM')
        User.objects.create(username='b', password='b', email='b@hotmail.com')

    def test_create_page(self):
        """
        Ensure only authenticated users can create a new page object.
        """
        url = reverse('page-list')

        # See if unauthenticated unadmin users can create a page (they shouldn't.)
        data = {'location': 1, 'pageName': 'Test Page 1', 'pageDescription': 'This is the first test page', 'pageCode': 'TP1'}
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

        # See if authenticated users can create a page (they should).
        print(User.objects.get().username)
        self.client.login(username='b', password='b')
        response = self.client.post(url, data, format='json')
        print(response.data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

这是我的views.py/视图集:

class IsAuthenticated(permissions.BasePermission):

    def has_permission(self, request, view):
        print('here!!!!!!!!!!!!')
        print(request.user)
        return request.user.is_authenticated()

class pageViewSet(viewsets.ModelViewSet):
    queryset = Page.objects.all()
    serializer_class = PageSerializer
    permission_classes = (IsAuthenticated,)

问题是,即使我通过 self.client.login(username='b', password='b') 登录用户,它在发帖时仍然会引发 403 错误。这是打印的内容:

here!!!!!!!!!!!!
AnonymousUser
b
here!!!!!!!!!!!!
AnonymousUser
{'detail': 'Authentication credentials were not provided.'}

如您所见,Django 确实看到了用户对象(因为它打印了 'b'),但是用户由于某种原因没有登录并且仍然是 AnonymousUser。现在,当我将我的设置更改为:

def setUp(self)
    url = reverse('user-list')

    # Create the user using the API.
    data = {'username': 'b', 'password': 'b', 'email': 'a@hotmail.com', 'location': '1'}
    response = self.client.post(url, data, format='json')
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)

然后让用户登录,它工作得很好并且测试没有引发任何错误。知道为什么在使用 User.objects.create() 创建用户时会引发错误吗?

我之前在其他单元测试中使用过类似的代码 类(使用 ORM 创建用户,然后让他登录)并且它有效。我不确定为什么它在这里不起作用。

编辑:此外,如果我创建用户并让他成为超级用户并让他登录,就像这样:

User.objects.create_superuser(username='a', password='a', email='a@hotmail.com')

同样有效。

找到答案了。我必须通过这样做来创建用户:

User.objects.create_user()

而不是这个:

User.objects.create()