如何更改DjangoRestFramework序列化程序的“此字段是必需的”错误消息?

如何更改DjangoRestFramework序列化程序的“此字段是必需的”错误消息?,第1张

概述当用户通过 JSON用户对象向后端提交表单时,这是处理它的视图: class user_list(APIView): """ Create a new user. """ def post(self, request): serializer = UserSerializer(data=request.DATA) if serial 当用户通过 JSON用户对象向后端提交表单时,这是处理它的视图:

class user_List(APIVIEw):    """    Create a new user.    """    def post(self,request):        serializer = UserSerializer(data=request.DATA)        if serializer.is_valID():            serializer.save()            return Response(serializer.data,status=status.http_201_CREATED)        return Response(serializer.errors,status=status.http_400_BAD_REQUEST)

我的问题是,如果用户没有填写表单中的某个字段,DRF发送给前端的错误消息是“此字段是必需的”.有没有办法让我更改它,以便对于所有字段,错误消息是“{fIEldname}是必需的.”?

这是我的serializers.py:

from rest_framework import serializersfrom django.contrib.auth.models import Userfrom CMSApp.mixins import SetCustomErrorMessagesMixinfrom django.utils.translation import gettext as _from rest_framework.valIDators import UniqueValIDatorfrom django.core.valIDators import RegexValIDatorclass UserSerializer(SetCustomErrorMessagesMixin,serializers.ModelSerializer):    class Meta:        model = User        fIElds = ('username','password','email','userextended')        extra_kwargs = {                    'password': {                        'write_only': True,}                }        custom_error_messages_for_valIDators = {            'username': {                UniqueValIDator: _('This username is already taken. Please try again.'),RegexValIDator: _('InvalID username')            }        }    def create(self,valIDated_data):        user = User.objects.create_user(            email = valIDated_data['email'],username = valIDated_data['username'],password = valIDated_data['password'],)        return user

这是SetCustomErrorMessageMixin:

class SetCustomErrorMessagesMixin:    """    Replaces built-in valIDator messages with messages,defined in Meta class.     This mixin should be inherited before the actual Serializer class in order to call __init__ method.    Example of Meta class:    >>> class Meta:    >>>     model = User    >>>     fIElds = ('url','username','groups')    >>>     custom_error_messages_for_valIDators = {    >>>         'username': {    >>>             UniqueValIDator: _('This username is already taken. Please,try again'),>>>             RegexValIDator: _('InvalID username')    >>>         }    >>>     }    """    def __init__(self,*args,**kwargs):        # noinspection PyArgumentList        super(SetCustomErrorMessagesMixin,self).__init__(*args,**kwargs)        self.replace_valIDators_messages()    def replace_valIDators_messages(self):        for fIEld_name,valIDators_lookup in self.custom_error_messages_for_valIDators.items():            # noinspection PyUnresolvedReferences            for valIDator in self.fIElds[fIEld_name].valIDators:                if type(valIDator) in valIDators_lookup:                    valIDator.message = valIDators_lookup[type(valIDator)]    @property    def custom_error_messages_for_valIDators(self):        Meta = getattr(self,'Meta',None)        return getattr(Meta,'custom_error_messages_for_valIDators',{})

最后,这是我的models.py(UserExtended模型):

from django.db import modelsfrom django.contrib.auth.models import User# Create your models here.class color(models.Model):    colorname = models.CharFIEld(max_length=50,unique=True)    colorCode = models.CharFIEld(max_length=10,unique=True)class UserExtended(models.Model):    user = models.OnetoOneFIEld(User,related_name="userextended")    color = models.ForeignKey(color)
解决方法 您可以覆盖UserSerializer的__init __()方法以更改必填字段的默认错误消息.

我们将遍历序列化程序的字段并更改所需密钥的默认error_messagesvalue的值.

class UserSerializer(SetCustomErrorMessagesMixin,serializers.ModelSerializer):    def __init__(self,**kwargs):        super(UserSerializer,**kwargs) # call the super()         for fIEld in self.fIElds: # iterate over the serializer fIElds            self.fIElds[fIEld].error_messages['required'] = '%s fIEld is required'%fIEld # set the custom error message    ...
总结

以上是内存溢出为你收集整理的如何更改DjangoRestFramework序列化程序的“此字段是必需的”错误消息?全部内容,希望文章能够帮你解决如何更改DjangoRestFramework序列化程序的“此字段是必需的”错误消息?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1193465.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存