当前位置: 动力学知识库 > 问答 > 编程问答 >

Django Rest framwork validation: Mark field as error

问题描述:

I started using django-rest-framework for my application and I have a question regarding the serializer validaton.

In the docs I found this example for object validation:

from rest_framework import serializers

class EventSerializer(serializers.Serializer):

description = serializers.CharField(max_length=100)

start = serializers.DateTimeField()

finish = serializers.DateTimeField()

def validate(self, attrs):

"""

Check that the start is before the stop.

"""

if attrs['start'] > attrs['finish']:

raise serializers.ValidationError("finish must occur after start")

return attrs

This returns the following:

{"non_field_errors": ["finish must occur after start"]}

My question is, how can I find out which fields are responsible for the failed validation?

In this case attrs['start'] and attrs['finish'].

In the end I want something like this:

{"non_field_errors": ["finish must occur after start"],

"start": ["finish must occur after start"],

"finish": ["finish must occur after start"]}

So that I can mark the responsible form fields.

I hope the question is clear. Thanks!

网友答案:

When you are creating the ValidationError, you can pass in a dictionary instead of a string. The dictionary expects that the key is the field name, and the value is the error string.

def validate(self, attrs):
    """
    Check that the start is before the stop.
    """
    if attrs['start'] > attrs['finish']:
        raise serializers.ValidationError({"finish": "finish must occur after start"})
    return attrs

This should produce output along the lines of:

{"start": ["finish must occur after start"], 
 "finish": ["finish must occur after start"]}

Which sounds like what you are looking for.

分享给朋友:
您可能感兴趣的文章:
随机阅读: