Allow empty strings on serializers

45 views
Skip to first unread message

Felipe Nogueira de Souza

unread,
May 18, 2020, 7:46:04 PM5/18/20
to Django REST framework
Hey guys, hope you're all good!

I'm having problems with the serialization of empty strings on DRF.

I have a model with two fields that are defined as blank = True and null = True, date and message.

models.py

class ContactUs(models.Model):
    email = models.CharField(_('email'), max_length=100)
    date = models.DateField(_('event date'), blank=True, null=True)
    message = models.CharField(_('message'), blank=True, null=True, max_length=2048)



In my serializer, I defined these fields as required = False and allow_null = True.

serializers.py



class
ContactUsSerializer(serializers.ModelSerializer):
message = serializers.CharField(required=False, allow_null=True)
date = serializers.DateField(required=False, allow_null=True)

class Meta:
model = ContactUs
fields = '__all__'



When the frontend does not send these fields or send them = null everything works 100%, however when it sends an empty string "" the serializer raises a validation error. I saw that I can handle this by defining to_internal_value (), but I think there may be a simpler way.

Does anyone have any other tips on how to solve this?

Shouldn't have an allow_empty=True option?

Thx,
Felipe

Felipe Nogueira de Souza

unread,
May 18, 2020, 7:55:59 PM5/18/20
to Django REST framework
Searching for this I discovered that there is an option allow_blank that works fine to CharField, but not for DateField.

sebastian wrzalek

unread,
May 18, 2020, 8:00:31 PM5/18/20
to django-res...@googlegroups.com
Hi, solution that comes to my mind is default value in your model fields.

--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-rest-framework/e1cc6978-a03f-478d-9ac9-7179753451fb%40googlegroups.com.

Felipe Nogueira de Souza

unread,
May 18, 2020, 9:13:55 PM5/18/20
to Django REST framework
Hum, I don't know, since this validation is made on the serializer, so I don't know if a default value on the model would help, but I'll try your suggestion anyway. 
Thx


Em segunda-feira, 18 de maio de 2020 20:46:04 UTC-3, Felipe Nogueira de Souza escreveu:
Reply all
Reply to author
Forward
0 new messages