Django将默认错误消息建模到一个字段中

时间:2016-05-23 09:58:52

标签: django django-models django-rest-framework

这个非常简单的django restframework代码。

models.py

class User(models.Model)
    Email = models.CharField(max_length=100)
    Username = models.CharField(max_length=100)
    State = models.CharField(max_length=100)

serializers.py

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('Email','Username','State')

views.py

class UserList(generics.ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

如果使用这个,我会收到像这样的错误

{
    "Email": [
        "This field may not be blank."
    ],
    "Username": [
        "This field may not be blank."
    ],
    "Country": [
        "This field may not be blank."
    ],
}

但是我需要像这样更改错误。如何我可以存档这个以及任何建议非常感谢。

{"error": 
    [
    "Email is required",
    "Username is required",
    "County is required"
    ]

}

2 个答案:

答案 0 :(得分:0)

您可以为任何错误案例定义自己的错误消息:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('Email','Username','State')

    def __init__(self, *args, **kwargs):
        super(UserSerializer, self).__init__(*args, **kwargs)
        for field in self.Meta.fields:
            self.fields[field].error_messages['required'] = "%s is required" % field

答案 1 :(得分:0)

您始终可以从通用视图覆盖创建/更新方法。它会是这样的:

class UserList(generics.ListCreateAPIView):

    queryset = User.objects.all()
    serializer_class = UserSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if not serializer.is_valid(raise_exception=False):
            # TODO: add here your custom error dict using serializer.errors
            return Response({"error":...}, status=...)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

或者......您可以尝试覆盖序列化程序...如果您不想覆盖视图。

(但是,JS开发人员必须有充分的理由不能解析一个简单的json错误对象:P)

希望这有帮助