[Django]-Changing field in Django Form, overriding clean()

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.

1👍

Clean data is runs before the is_valid, because clean is one of many methods that django runs to validate your form

since you cleaning just one field, use clean to this field

class BokningForm(ModelForm)
    ...

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

in your views maybe this can workout

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

EDIT: Got some good info in other post… try use clean method inside the model, looks like this runs first

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

Source: Django: Model clean method called before form clean

Leave a comment