Luis Ferrer Luis Ferrer - 4 months ago 14
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
first_name
,
last_name
, and
email
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
blank
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
save()
function on a
BaseModel
class and check that all CharFields are filled or raise an error otherwise.

Thoughts? Thanks in advance!

Answer

Why it happens is explained here: https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.Field.null

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

Comments