Django Rest Framework – 自定义错误消息 – 序列化器 vs. 模型

huangapple go评论59阅读模式
英文:

Django Rest Framework - Custom error messages - Serializer vs. Model

问题

Django Rest Framework – 自定义错误消息 – 序列化器 vs. 模型 你好!

我目前面临一个问题,我无法通过查阅文档或其他问题来解决,如果有人能帮助我,我将非常感激。

问题相对简单:当发布新对象时,我正在添加自定义消息以解决验证错误的问题,但我希望只在一个地方执行此操作:在模型内部或在序列化器内部。

针对本示例和我的用例,我只讨论uniquemax_length验证。

  • 在模型字段内定义error_messages=errors_dict目前仅更改unique验证错误消息,显示max_length的默认消息。

  • 当我在序列化器内部使用extra_kwargs在Meta中设置它时,仅更改max_length验证错误消息。

有谁知道我在这里遗漏了什么?是否可能只在一个地方设置error_messages

谢谢!


以下是一些代码片段,如果有帮助的话:

在下面的示例中,errors是相同的字典,包含两个键(uniquemax_length)。

  • 在模型内部,仅适用于唯一验证:
class User(AbstractUser, SplintModel):
    (...)
    cpf = models.CharField('CPF', blank=False, max_length=11, unique=True, error_messages=errors)
  • 在序列化器内部,仅适用于max_length验证:
class UserSerializer(serializers.ModelSerializer):
    (...)
    class Meta:
        model = User
        (...)

        extra_kwargs = {
            "cpf": {"error_messages": errors}
        }
英文:

Django Rest Framework – 自定义错误消息 – 序列化器 vs. 模型 Hello!

I'm currently facing a problem that I am not being able to solve by searching the documentation or other questions, if someone can help I would be very grateful.

The problem is relatively of simple: I am adding custom messages for validation errors that come up when posting a new object, but I'd like to do it in one place only: inside model OR inside serializer.

For the sake of this example and my use case, I am talking only about unique and max_length validations.

  • Defining error_messages=errors_dict inside the model fields currently only changes the unique validation error message, displaying the default for max_length.

  • The opposite happens when I set it inside the serializer, using extra_kwargs inside Meta. It only changes the max_length validation error message.

Does anyone know what I am missing here? Is it possible to set the error_messages in only one place?

Thank you!


Here are some code snippets, if it helps:

errors in the below examples is the same dictionary, containing both keys (unique and max_length).

  • Inside Model, working only for the unique validation:
class User(AbstractUser, SplintModel):
    (...)
    cpf = models.CharField('CPF', blank=False, max_length=11, unique=True, error_messages=errors)
  • Inside Serializer, working only for the max_length validation:
class UserSerializer(serializers.ModelSerializer):
    (...)
    class Meta:
        model = User
        (...)

        extra_kwargs = {
            "cpf": {"error_messages": errors}
        }

答案1

得分: 0

尝试在你的 serializers.py 中添加以下代码:

from rest_framework.validators import UniqueValidator

extra_kwargs = {
    'cpf': {
        'error_messages': {"max_length": "你的错误信息"},
        'validators': [
            UniqueValidator(
                queryset=User.objects.all(),
                message="在此处写下你的错误消息"
            )
        ]
    }
}
英文:

try this in your serializers.py:

from rest_framework.validators import UniqueValidator

    extra_kwargs = {
       'cpf': { 
                {
                  'error_messages' : {"max_length": "your error"},
                  'validators': [
                      UniqueValidator(
                         queryset=User.objects.all(),
                         message="write your error message here"
                )
             ]
        }
     }

huangapple
  • 本文由 发表于 2023年4月7日 02:52:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952840.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定