demux
demux

Reputation: 4654

Django Rest Framework's serializer.is_valid() raising validation errors even though required=false

I would like to have these fields optional in my form but...

Error:

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

Serializer:

class StudentSerializer(ModelSerializer):
    name = CharField(read_only=False, required=False, allow_null=True)
    user = StudentUserSerializer(read_only=True)
    invite = StudentInviteSerializer(read_only=True)

    email = CharField(read_only=False, required=False, allow_null=True)

    class Meta:
        model = Student
        fields = ('id', 'name', 'user', 'invite', 'email')

Upvotes: 1

Views: 4487

Answers (1)

Rahul Gupta
Rahul Gupta

Reputation: 47906

Try adding allow_blank=True in your serializer's name and email fields.

name = CharField(read_only=False, required=False, allow_null=True, allow_blank=True)

email = CharField(read_only=False, required=False, allow_null=True, allow_blank=True)

From http://www.django-rest-framework.org/api-guide/fields/#charfield

max_length - Validates that the input contains no more than this number of characters.
min_length - Validates that the input contains no fewer than this number of characters.
allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.
trim_whitespace - If set to True then leading and trailing whitespace is trimmed. Defaults to True.
The allow_null option is also available for string fields, although its usage is discouraged in favor of allow_blank. It is valid to set both allow_blank=True and allow_null=True, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.

Upvotes: 9

Related Questions