Search code examples
pythondjango

django: is it safe to remove `blank=True` from web-service only app?


I'm starting a project using an existing db. The models generated from inspectdb have

(...null=True, blank=True)

in various fields. The documentation mentions that the blank argument is related to django forms. I'm making a web service project, using django rest framework and the django ORM. Absolutely no view component (autogenerated forms, html templates, etc) of the MVC.

Does that mean it's safe to remove blank=True from my models?


Solution

  • Without blank=True your application will fail validation when trying to serialize data with blank fields. Django rest framework ModelSerializer enforces any kind of validation that is on the model fields. It works similarly to Django ModelForms.

    If you're not using ModelSerializers and try to save a blank value against a field without blank=True your save method will throw an exception instead.

    TL;DR: if you remove blank=True your DRF serializer will fail validation against empty fields.

    Take a look at this question on how validation works in DRF.

    Hope this helps!