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

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

问题描述

该方案非常简单:



我有一个需要的字段的模型。假设其中一个是 TextField ,不能为 blank
我还有一个代表该模型的 ModelSerializer (Django Rest Framework)。



当一个空的字符串用于通过序列化器设置该字段,返回的错误来自模型本身(此字段不能为空白)。



我只想在序列化器级别重写错误消息,而不需要明确地重新指定序列化程序中的每个字段(我认为是违反DRY原则),必须写一个验证_ 方法,并提出自己的 ValidationError 或者必须更改模型中的错误消息级别(因为有时错误信息的上下文对我的用例很重要,错误信息应该相应地)。



在其他有一种方法来重写序列化级别的错误消息,就像一个 ModelForm 一样简单:

  class MyModelForm(ModelFo rm):
class Meta:
model = MyModel
error_messages = {field1:{required:_(由于某种原因,这是覆盖模型默认值的自定义错误消息 )}}


解决方案

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



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

  class UserSerializer(ModelSerializer):

class Meta :
model = User
extra_kwargs = {username:{error_messages:{required:给自己一个用户名}}}
/ pre>

原始答案



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

  from rest_framework。序列化器导入ModelSerializer,ModelSerializerOptions 

class CustomErrorMessagesModelSerializerOptions(ModelSerializerOptions):

CustomErrorMessagesModelSerializerOptions的元类类选项

def __init __ ,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)

#运行Meta类中提供的所有错误消息,并更新
for field_name,err_dict in self.opts.error_message s.iteritems():
self.fields [field_name] .error_messages.update(err_dict)

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



全部留下来做,只是继承它,并做这样的事情:

  class UserSerializer(CustomErrorMessagesModelSerializer):
类Meta:
model =用户
error_messages = {username:{required:给自己一个用户名}}


The scenario is quite straight-forward:

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).

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).

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")}}

解决方案

EDIT: 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.

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"}}}

Original answer:

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)

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天全站免登陆