Luis Ferrer Luis Ferrer - 7 months ago 22
Python Question

Django raise Exception on blank CharFields

I am using Django and the REST Framework to build an API that serves data to an AngularJS website. I need to make sure that all validation gets done on the back-end.

I have a model named Candidate:

class Candidate(CreatedModel):

first_name = CharField(max_length=30)
last_name = CharField(max_length=100)
email = CharField(max_length=254, unique=True)
phone = CharField(max_length=20, null=True)
resume_path = CharField(max_length=200, null=True)
notes = TextField(null=True)

In the model, only
, and
are required. The rest of the fields can be null.

Then I run the server and make a test POST request to create a new Candidate. The problem is that even if I do not specify any field, it will simply give them all empty string values (

I heard of the
attribute for Django Model Fields, but it only applies to validation in forms and not for HTTP requests.

Right now the only way it seems I can solve the issue is by overriding the
function on a
class and check that all CharFields are filled or raise an error otherwise.

Thoughts? Thanks in advance!


Why it happens is explained here:

Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL.

if you don't want empty strings to be in your database, you can simply mark the field as required in your form. Or use DRF validators