Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 836
Kluckmuck Avatar asked Oct 16 '25 01:10

Kluckmuck


1 Answers

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.

like image 80
Daniel Roseman Avatar answered Oct 18 '25 17:10

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!