Opened 4 years ago

Closed 4 years ago

#32286 closed Uncategorized (invalid)

Definition of JSONField causes issue with validation for a Falsey value

Reported by: Adam Carruthers Owned by: nobody
Component: Forms Version: 3.1
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I ran into this issue while trying to create a JSONField that would contain a list of strings. The list of strings could have any length. I used the following:

model_field = models.JSONField(validator=[MyCustomValidator()])

The validator checks that the object is a list of strings along with some other stuff.

However, under this configuration, [] was not a valid entry because it was falsey and hence it failed the blank=False test.

So I set blank=True on the field to allow for []. But this led to the problem that if you have a falsey value then the validators aren't run. So I was able to set the field to be null on the admin site and it was permitted. But I really don't want to allow null as a value for fear of causing bugs in my code that uses the API. Even worse an empty string "" was allowed!

As it is, as far as I can tell, there is no way to create a field level validator that allows empty list and does not allow null. You could probably use a model level validator but that is non-ideal, and this feels like a potential way for bugs to emerge on a website.

Change History (1)

comment:1 by Mariusz Felisiak, 4 years ago

Component: UncategorizedForms
Resolution: invalid
Status: newclosed

Yes, Django doesn't run validators on empty values, however you can create a custom form field and change empty_values to the ([],), see #19997 and an example in tests. Please use one of support channels if you have further questions.

Note: See TracTickets for help on using tickets.
Back to Top