Validating ModelChoiceField in Django forms
- by Andrey
I'm trying to validate a form containing a ModelChoiceField:
state = forms.ModelChoiceField(queryset=State.objects.all(), empty_label=None)
When it is used in normal circumstances, everything goes just fine. But I'd like to protect the form from the invalid input. It's pretty obvious that I must get forms.ValidationError when I put invalid value in this field, isn't it? But if I try to submit a form with a value 'invalid' in 'state' field, I get
ValueError: invalid literal for int() with base 10: 'invalid'
and not the expected forms.ValidationError. What should I do? I tried to place a def clean_state(self) to check this field but that didn't work plus I don't think this is a good solution, there must be something more simple but I just missed that.