I have a Django form like this.
class TransactionForm(forms.Form):
start = forms.DateField()
end = forms.DateField()
I wanted to change the value before running validation:
def clean_start(self):
start = sef.cleaned_data.get('start')
return bs_to_ad(start) #This function returns date in 'YYYY-MM-DD' format
The problem is that this method runs in forms.ModelForm object but doesn't in forms.Form object.
CodePudding user response:
You can modify the data before calling __init__
method using a custom __init__
method like this
class TransactionForm(forms.Form):
start = forms.DateField()
end = forms.DateField()
def __init__(self, **kwargs):
if "data" in kwargs:
start = kwargs.get("data").get("start")
# modify start
kwargs["data"]["start"] = start
super().__init__(self, **kwargs)
CodePudding user response:
Simply doing this works fine.
class TransactionFrom(forms.Form):
start = forms.DateField()
end = forms.DateField()
def clean(self):
data = self.cleaned_data
if 'start' in data.keys():
start = bs_to_ad(data.get('start'))
if 'end' in data.keys():
end = bs_to_ad(data.get('end'))
self.cleaned_data.update({'start': start, 'end': end})