Serializer.is_valid()引发Queryset错误,而serializer.is_valid(raise_exception = True)不

时间:2016-09-06 10:16:04

标签: django django-rest-framework django-rest-auth

这里的问题很容易解决,我打开它的原因是我不明白发生了什么。

这里是来自django-rest-auth:

的代码
class PasswordResetView(GenericAPIView):

    """
    Calls Django Auth PasswordResetForm save method.

    Accepts the following POST parameters: email
    Returns the success/fail message.
    """

    serializer_class = PasswordResetSerializer
    permission_classes = (AllowAny,)

    def post(self, request, *args, **kwargs):
        # Create a serializer with request.data
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        serializer.save()
        # Return the success message with OK HTTP status
        return Response(
            {"success": _("Password reset e-mail has been sent.")},
            status=status.HTTP_200_OK
        )

这是整个班级,它确实运作良好。

我制作了一个小改动副本 - 而不是serializer.is_valid(raise_exception=True)我展开它:

if serializer.is_valid():
    serializer.save()
    # Return the success message with OK HTTP status
    return Response(
        {"success": _("Password reset e-mail has been sent.")},
        status=status.HTTP_200_OK
    )
else:
    return Response(
        {"error": "Something's wrong."},
        status=status.HTTP_400_BAD_REQUEST
    )

当我运行它时,我得到了

*AssertionError: 'PasswordResetView' should either include a `queryset` attribute, or override the `get_queryset()` method.*

唯一的区别在于使用serializer.is_valid(raise_exception=True) (Ok) or just serializer.is_valid()(失败)。

有人可以向我解释一下吗?这不是我第一次看到这样的问题。

当然我可以写一个空的def get_quesryset(): return None来修复它。 但原始代码没有get_queryset或get_object或其他任何东西,并且工作正常。

谢谢!

编辑:这是我的代码,以便您可以看到它与原始代码完全相同。

class PasswordResetView(GenericAPIView):

    """
    Calls Django Auth PasswordResetForm save method.

    Accepts the following POST parameters: email
    Returns the success/fail message.
    """

    serializer_class = PasswordResetSerializer
    permission_classes = (AllowAny,)

    def post(self, request, *args, **kwargs):
        # Create a serializer with request.data
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            # Return the success message with OK HTTP status
            return Response(
                {"success": _("Password reset e-mail has been sent.")},
                status=status.HTTP_200_OK
            )
        else:
            return Response(
                {"error": "Something's wrong."},
                status=status.HTTP_400_BAD_REQUEST
            )

0 个答案:

没有答案