Customize serializer errors with incorrect data

瀏覽次數:15 次
跳到第一則未讀訊息

Sencer Hamarat

未讀,
2022年8月3日 凌晨1:00:122022/8/3
收件者:django...@googlegroups.com
Hi,

I found a way to customize error messages of the serializer by adding extra_kwargs into the serializer meta class.

But, I'm wishing to render custom serializer errors with the incorrect data. For example:

class CreateUserSerializer(serializer.ModelSerializer):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'is_active', 'email')

def create_users(request):
    ...
    serialized_data = CreateUserSerializer(data=data, many=True)
    if serialized_data.is_valid():
        serialized_data.save()

Say, afew of the user data has no email information.
This will return error like:

{"email":["This field may not be blank."], "email":["This field may not be blank."], ...}

I want to add error related data or at least index number to error text

Is there a way to do that?

Kind regards,
Sencer HAMARAT

Sencer Hamarat

未讀,
2022年8月4日 凌晨3:51:272022/8/4
收件者:django...@googlegroups.com
Hello again,

For anyone interested, more detailed version was sent to stackoverflow:

Kind regards,
Sencer HAMARAT


Ammar Mohammed

未讀,
2022年8月4日 凌晨4:35:552022/8/4
收件者:django...@googlegroups.com

Hello Sencer
You can add cuatom functions to your serializer to return the data with the zerializer .

For example you can add :
def email_serializer(email):
   if !email.endswith("gmail.com"):
     raise SerializerError("Error wrong email address : ", email)

This is just an example your functions can look in and way.

In the email field in your serializer you ahould add the "email_serializer" function to the serializers.

Regards
--

Ammar Mohammed

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACp8TZjwjk6yFAq%2B%3Dw9W6sKeX%3Dg%2Bx8k%3DHJf3bpMpJaOSMqyTAg%40mail.gmail.com.
回覆所有人
回覆作者
轉寄
0 則新訊息