首页 > 解决方案 > Changing field in Django Form, overriding clean()

问题描述

I have a date, passed as 2019-01-01T00:02. My objective is to replace the T with a whitespace, 2019-01-01 00:02.

Using Form, i validate that field and some others.'

klientForm = KlientForm(json.loads(request.body.decode()))
bokningForm = BokningForm(json.loads(request.body.decode()))
if klientForm.is_valid() and bokningForm.is_valid():
    #Save model, etc.

I'm using DateTimeField, and it will not accept the date unless I change it like above. I implemented my own clean() method,

def clean(self):
    cleaned_data = super(BokningForm, self).clean()
    pumpStart = self.data['pumpStart']
    pumpStart = pumpStart.replace("T", " ")
    cleaned_data['pumpStart'] = datetime.strptime(pumpStart, "%Y-%m-%d %H:%M")
    return cleaned_data

This successfully converts it to a datetime object, I checked using print(cleaned_data)

My issue is that the data is returned to late, as (I think) bokningForm.is_valid() has already failed, resulting in the model not being saved.

I tried using clean_pumpStart(self): as in Django Forms but the function was not called when bokningForm.is_valid() failed, resulting in the same issue as above.

Any help appreciated!

标签: pythonjsondjangovalidationdatetime

解决方案


You don't need to do any of this. Instead, you should redefine the field itself, supplying the input_formats attribute:

class BokningForm(forms.ModelForm):
    pumpStart = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M:%S'])
    ...

Now Django will convert the value automatically as part of its own validation process.

Note, if what you're doing is validating JSON, you probably want to use Django REST Framework and its serializers, rather than plain Django forms.


推荐阅读