Validating ModelChoiceField in Django forms

Posted by Andrey on Stack Overflow See other posts from Stack Overflow or by Andrey
Published on 2010-03-08T10:16:03Z Indexed on 2010/03/08 10:21 UTC
Read the original article Hit count: 765

Filed under:
|
|
|
|

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.

© Stack Overflow or respective owner

Related posts about django

Related posts about python