Home > Blockchain >  How to validate a field with uppercase with django serializers
How to validate a field with uppercase with django serializers

Time:10-27

I am programming an API and I have noticed the following error when debugging. The following code does not validate the Status field

class DocumentSalesforceSerializer(serializers.Serializer):
    AccountId = serializers.CharField(required=True)
    ContactId = serializers.CharField(required=True)
    Status = serializers.CharField(required=True)
    StartDate = serializers.CharField(required=True)
    EndDate = serializers.CharField(required=True, allow_blank=True)
    Subject = serializers.CharField(required=True)

    def validate_status(self, Status):
        if Status not in ("New", "In Progress", "On Hold", "Completed", "Closed", "Cannot Complete", "Canceled"):
            raise serializers.ValidationError("Invalid Status")
        return Status

But, when I change the word "Status" to "status" like this:

class DocumentSalesforceSerializer(serializers.Serializer):
    AccountId = serializers.CharField(required=True)
    ContactId = serializers.CharField(required=True)
    status = serializers.CharField(required=True)
    StartDate = serializers.CharField(required=True)
    EndDate = serializers.CharField(required=True, allow_blank=True)
    Subject = serializers.CharField(required=True)

    def validate_status(self, status):
        if status not in ("New", "In Progress", "On Hold", "Completed", "Closed", "Cannot Complete", "Canceled"):
            raise serializers.ValidationError("Invalid Status")
        return status

Everything is working perfectly fine. Can anyone tell me why is it working like that and how can I do to validate the "Status" uppercase field? Thanks

CodePudding user response:

It's because the name of the attribute inside your model. You should follow the same naming convention you followed in your model. You have two ways to solve your problem:

  1. Go to your model, and change status to Status

  2. Use this in your serializer:

    Status = serializers.CharField(required=True, source='status')
    

CodePudding user response:

The following code does not validate the Status field.

It expects that the validator is named validate_Status, so with an uppercase S as well:

class DocumentSalesforceSerializer(serializers.Serializer):
    AccountId = serializers.CharField(required=True)
    ContactId = serializers.CharField(required=True)
    Status = serializers.CharField(required=True)
    StartDate = serializers.CharField(required=True)
    EndDate = serializers.CharField(required=True, allow_blank=True)
    Subject = serializers.CharField(required=True)

    def validate_Status(self, Status):
        if Status not in ("New", "In Progress", "On Hold", "Completed", "Closed", "Cannot Complete", "Canceled"):
            raise serializers.ValidationError("Invalid Status")
        return Status
  • Related