英文:
Django Rest Framework - Custom error messages - Serializer vs. Model
问题
你好!
我目前面临一个问题,我无法通过查阅文档或其他问题来解决,如果有人能帮助我,我将非常感激。
问题相对简单:当发布新对象时,我正在添加自定义消息以解决验证错误的问题,但我希望只在一个地方执行此操作:在模型内部或在序列化器内部。
针对本示例和我的用例,我只讨论unique
和max_length
验证。
-
在模型字段内定义
error_messages=errors_dict
目前仅更改unique
验证错误消息,显示max_length
的默认消息。 -
当我在序列化器内部使用
extra_kwargs
在Meta中设置它时,仅更改max_length
验证错误消息。
有谁知道我在这里遗漏了什么?是否可能只在一个地方设置error_messages
?
谢谢!
以下是一些代码片段,如果有帮助的话:
在下面的示例中,errors
是相同的字典,包含两个键(unique
和max_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}
}
英文:
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 theunique
validation error message, displaying the default formax_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"
)
]
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论