开发者

Alternative text in Django forms for None value in DateField

开发者 https://www.devze.com 2023-03-11 07:08 出处:网络
I\'d like to display an alternative text (let\'s say \'any\') for no or empty value in a DateField\'s TextInput widget.

I'd like to display an alternative text (let's say 'any') for no or empty value in a DateField's TextInput widget.

My idea was to set the form field's initial value to 'any' and then check in its clean_<field>() method for this initial value and cleaning it back to None:

date_field = forms.DateField(initial='any', required=False)

def clean_date_field(self):
    data = self.cleaned_data['date_field']
    if data == 'any':
        data = None
    return data

Unfortunately, the clean_<field>() method is never called, I think because some date format validation takes place in advance and raises a ValidationError which will prevent the clean_<field>() method from ever being called.

Is there a 开发者_Python百科simple way to display an alternative form field value for None using a DateField?

Any hints are appreciated.


You can create custom field and override to_python method. to_python will be called before field's clean, and you can convert any to None value there.

def to_python(self, value):
    if value == 'any':
        value = None
    return super(CustomField, self).to_python(value)

Also you can use HTML5 placeholder.

0

精彩评论

暂无评论...
验证码 换一张
取 消