Django Rest Framework 序列化程序中的自定义错误消息 [英] Custom error messages in Django Rest Framework serializer

查看:34
本文介绍了Django Rest Framework 序列化程序中的自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景非常简单:

我有一个模型,其中包含一些必填字段.假设其中一个是 TextField,它不能是 blank.我还有一个代表该模型的 ModelSerializer(Django Rest Framework).

I have a model with some fields that are required. Let's say one of them is a TextField which can't be blank. I also have a ModelSerializer (Django Rest Framework) that represents that model.

当使用空字符串通过序列化程序设置该字段时,返回的错误来自模型本身(此字段不能为空).

When an empty string is used to set that field through the serializer the error returned comes from the model itself (This field can't be blank).

我只想在序列化程序级别覆盖错误消息,而无需明确重新指定序列化程序中的每个字段(我认为这违反了 DRY 原则),而必须编写 validate_ 每个字段的方法并引发我自己的 ValidationError 或必须更改 Model 级别的错误消息(因为有时错误消息的上下文对我的使用很重要-case 并相应地给出错误信息).

I would like to override the error messages only in the serializer level, without the need to explicitly re-specifying every field in the serializer (which I believe is against the DRY principle), having to write a validate_ method for each field and raise my own ValidationError or having to change the error messages in the Model level (because sometimes the context of the error message matters to my use-case and the error message should be given accordingly).

换句话说,是否有一种方法可以像在 ModelForm 中一样简单地覆盖序列化程序级别的错误消息:

In other words, is there a way to override error messages in the serializer level as easy as it is for a ModelForm:

class MyModelForm(ModelForm):
    class Meta:
        model = MyModel
        error_messages = {"field1": {"required": _("For some reason this is a custom error message overriding the model's default")}}

推荐答案

我看到这个问题仍然收到一些意见,所以重要的是要注意还有另一种方法,比我在这里发布的原始答案.

I see that this question still receives some views, so it is important to note that there's another approach, much cleaner than the original answer I posted here.

您可以只使用 extra_kwargs 序列化器 Meta 类的属性,如下所示:

You can just use the extra_kwargs attribute of the serializer's Meta class, like so:

class UserSerializer(ModelSerializer):

    class Meta:
        model = User
        extra_kwargs = {"username": {"error_messages": {"required": "Give yourself a username"}}}

原答案:

使用@mariodev 的回答,我在我的项目中创建了一个新类:

Using @mariodev 's answer I created a new class in my project that does that:

from rest_framework.serializers import ModelSerializer, ModelSerializerOptions

class CustomErrorMessagesModelSerializerOptions(ModelSerializerOptions):
    """
    Meta class options for CustomErrorMessagesModelSerializerOptions
    """
    def __init__(self, meta):
        super(CustomErrorMessagesModelSerializerOptions, self).__init__(meta)
        self.error_messages = getattr(meta, 'error_messages', {})

class CustomErrorMessagesModelSerializer(ModelSerializer):
    _options_class = CustomErrorMessagesModelSerializerOptions

    def __init__(self, *args, **kwargs):
        super(CustomErrorMessagesModelSerializer, self).__init__(*args, **kwargs)

        # Run through all error messages provided in the Meta class and update
        for field_name, err_dict in self.opts.error_messages.iteritems():
            self.fields[field_name].error_messages.update(err_dict)

第一个提供了向序列化程序添加新的 Meta 类属性的可能性,就像 ModelForm 一样.第二个继承自 ModelSerializer 并使用@mariodev 的技术来更新错误消息.

The first one gives the possibility to add a new Meta class attribute to the serializer as with the ModelForm. The second one inherits from ModelSerializer and uses @mariodev's technique to update the error messages.

剩下要做的就是继承它,然后做类似的事情:

All is left to do, is just inherit it, and do something like that:

class UserSerializer(CustomErrorMessagesModelSerializer):
    class Meta:
        model = User
        error_messages = {"username": {"required": "Give yourself a username"}}

这篇关于Django Rest Framework 序列化程序中的自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆