社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

在Django REST框架中,如何调用序列化程序的validate方法并验证提交的必填字段?

Dave • 4 年前 • 1689 次点击  

我正在使用Python3.9和Django REST框架(V3.12.2)。在一个视图中,我验证了对象字段是否正确提交,如下所示。。。

@api_view(('POST',))
def save_to_sheet_from_form(request):
    valid_ser = ValidateNewCoopSerializer(data=request.data)
    if valid_ser.is_valid():
        ... do valid actions ...
        return Response(post_data, status=status.HTTP_201_CREATED)
    else:
        return Response(valid_ser.errors, status=status.HTTP_400_BAD_REQUEST)

我的序列化程序设置如下。。。

class ValidateNewCoopSerializer(serializers.Serializer):
    # Set all fields as not required and allow_blank=true, so we can combine all validation into one step
    id=serializers.CharField(required=False, allow_blank=True)
    coop_name=serializers.CharField(required=False, allow_blank=True)
    street=serializers.CharField(required=False, allow_blank=True)
    address_public=serializers.CharField(required=False, allow_blank=True)
    city=serializers.CharField(required=False, allow_blank=True)
    state=serializers.CharField(required=False, allow_blank=True)
    zip=serializers.CharField(required=False, allow_blank=True)
    county=serializers.CharField(required=False, allow_blank=True)
    country=serializers.CharField(required=False, allow_blank=True)
    websites=serializers.CharField(required=False, allow_blank=True)
    contact_name=serializers.CharField(required=False, allow_blank=True)
    contact_name_public=serializers.CharField(required=False, allow_blank=True)
    contact_email=serializers.CharField(required=False, allow_blank=True)
    contact_email_public=serializers.CharField(required=False, allow_blank=True)
    contact_phone=serializers.CharField(required=False, allow_blank=True)
    contact_phone_public=serializers.CharField(required=False, allow_blank=True)
    entity_types=serializers.CharField(required=False, allow_blank=True)
    scope=serializers.CharField(required=False, allow_blank=True)
    tags=serializers.CharField(required=False, allow_blank=True)
    desc_english=serializers.CharField(required=False, allow_blank=True)
    desc_other=serializers.CharField(required=False, allow_blank=True)
    req_reason=serializers.CharField(required=False, allow_blank=True)

    def validate(self, data):
        """
        Validation of start and end date.
        """
        errors = {}

        # required fields
        required_fields = ['coop_name', 'websites', 'contact_name', 'contact_name_public', 'entity_types', 'req_reason']
        for field in required_fields:
            if not data[field]:
                errors[field] = 'This field is required.'

        # contact info
        contact_email = data['contact_email'] if 'contact_email' in data else None
        contact_phone = data['contact_phone'] if 'contact_phone' in data else None
        if not contact_email and not contact_phone:
            errors['contact'] = 'Either contact phone or contact email is required.'

        if errors:
            raise serializers.ValidationError(errors)

        return data

问题是我必须将这些行添加到我的验证方法中。。。

    required_fields = ['coop_name', 'websites', 'contact_name', 'contact_name_public', 'entity_types', 'req_reason']
    for field in required_fields:
        if not data[field]:
            errors[field] = 'This field is required.'

我觉得有点草率,因为我可以定义字段定义中需要的内容,就像这样

coop_name=serializers.CharField()

但如果我这样做,那么似乎序列化程序的“验证”方法不会被调用,尤其是这个逻辑

    contact_email = data['contact_email'] if 'contact_email' in data else None
    contact_phone = data['contact_phone'] if 'contact_phone' in data else None
    if not contact_email and not contact_phone:
        errors['contact'] = 'Either contact phone or contact email is required.'

有没有办法定义所需的字段并调用序列化程序的validate方法?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130839
文章 [ 1 ]  |  最新文章 4 年前
Ashin Shakya
Reply   •   1 楼
Ashin Shakya    5 年前

我认为当使用序列化程序时。序列化程序如果它是必需的,则必须显式定义required=True,否则默认情况下它将始终为required=False。

coop_name = serializers.CharField() # Default required=False

也可以尝试添加

def validate(self, data):
    validated_data = super().validate(data)

    # Other validation here
    ...

    return validated_data