简体   繁体   中英

Django forms: get the value of a forms.CharField as a date

I have a form that has a CharField input for an european date.

I need to transform it to a date python object.

Is there a way to let the form care about it, in the validation? some callback?

I don't want to do it in the view when there's the form processing.

That's what the clean_FOO hook is for which populates the cleaned_data dict.

class MyFrom(..):
    field = forms....

    def clean_field(self):
        data = self.cleaned_data.get('field')
        try:
            return datetime.datetime.strptime(data)
        except Exception:
             raise forms.ValidationError("That ain't no time!")

为什么不只是DateField呢?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM