Opened 11 years ago

Closed 11 years ago

#22739 closed Bug (wontfix)

CharField for Forms raises on empty string

Reported by: jeremyt Owned by: nobody
Component: Forms Version: 1.6
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

forms.CharField raises a ValidationError when the min_length is zero and it receives an empty string. Receiving an empty string is not the same as the argument not being present in the arguments.

In cases,

PUT requests on a REST resource. Not sending a CharField means, do nothing to that field but sending a blank string is an attempt to set a field to an empty string.

In a web form, I may want to require a field be present in the POST data as it is a part of my form but it may be blank/empty. If that field is not present, this means that the data isn't returning the fields in which I have set as required.

>>> from django import forms
>>> forms.CharField(min_length=0).clean("")
django.core.exceptions.ValidationError: [u'This field is required.']

Change History (1)

comment:1 by Sasha Romijn, 11 years ago

Resolution: wontfix
Status: newclosed

I can see your point, but the required check has been specifically written to fail on an empty string as if it had been missing. Each field defines a set of empty_values, with the default including an empty string. If the value is in empty_values, this triggers the required error.

I don't really see a way to change this behaviour in Django without causing numerous other issues. However, a simple workaround would probably be for you to make your own subclass of forms.CharField, in which you override the empty_values attribute to only include None. You can then use that to only get the ValidationError when the value was absent instead of empty. This is not a public API as far as I can find, so it might change in the future.

Closing as wontfix, but please reopen if you disagree.

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