This should be pretty straightforward but I’m not figuring it out from the Django documentation. I have an IntegerField Model Field from which I’ve created a ModelForm Field. The field in question contains $ values (price) and it would be preferable from a UX standpoint if the user did not receive a error message (‘enter whole number’) when they input $10 instead of 10.
I’ve tried manual form cleaning but it seems that the clean_field method is run after other validation methods. My reading so far seems to confirm that as well.
def clean_bill(self):
bill = self.cleaned_data["bill"]
if '$' in bill:
bill=bill.replace('$','',1)
return bill
Is there a way around this while maintaining the IntegerField in the modelform? Should I just make it a RegexField?
EDIT: I ended up going with a combination of the above and a RegexField. Still curious if there is another/better way.
bill= forms.RegexField(label=_("Bill"), max_length=10,required=True, regex=r'^\$?[\d]+$',
error_messages = {'invalid': _("Please enter a whole number.")})
Create an IntegerField in the model, and a CharField in the form.
You can still use modelform to do this but you’ll have to:
try this and/or this