[Django]-Django–Form validation (Why can't I manually clean an Integer Form Field)

4👍

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:

  1. ‘exclude’ the model field from the form,
  2. write a clean_bill method in the form
  3. set the value of the model’s field to the parsed integer value

try this and/or this

1👍

Yes, you are right. According to the Django docs of form and field validation it will not even go to your clean method and already raise ValidationError in the first step (to_python method).
There is nothing much you can do on the form level I think. What you could do though is processing the POST data in the view before passing it to the form. Some simple example:

post_dict = request.POST.copy()   #makes a copy of request.POST so you can modify it
bill = post_dict['bill']
if '$' in bill:
    bill = bill.replace('$','',1)   
post_dict['bill'] = bill
# pass post_dict to your form instead of request.POST
...

Leave a comment