3

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!

4

2 回答 2

3

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.

于 2018-07-13T13:34:37.503 回答
1

清理数据在 is_valid 之前运行,因为清理是 django 运行以验证表单的众多方法之一

由于您只清理一个字段,因此请对该字段使用 clean

class BokningForm(ModelForm)
    ...

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

在你看来,也许这可以锻炼

if form.is_valid():
    bokning= form.save(commit=False)
    ... # Change your value
    bokning.save()

编辑:在其他帖子中获得了一些好的信息...尝试在模型中使用 clean 方法,看起来这个首先运行

class Bokning(models.Model):
    def clean(self):
        ...

资料来源:Django:在表单清理之前调用模型清理方法

于 2018-07-13T13:45:49.860 回答