Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django forms.ChoiceField without validation of selected value

Tags:

django

Django ChoiceField "Validates that the given value exists in the list of choices."

I want a ChoiceField (so I can input choices in the view) but I don't want Django to check if the choice is in the list of choices. It's complicated to explain why but this is what I need. How would this be achieved?

like image 353
Al Bundy Avatar asked Nov 04 '13 15:11

Al Bundy


1 Answers

You could create a custom ChoiceField and override to skip validation:

class ChoiceFieldNoValidation(ChoiceField):
    def validate(self, value):
        pass

I'd like to know your use case, because I really can't think of any reason why you would need this.

Edit: to test, make a form:

class TestForm(forms.Form):
    choice = ChoiceFieldNoValidation(choices=[('one', 'One'), ('two', 'Two')])

Provide "invalid" data, and see if the form is still valid:

form = TestForm({'choice': 'not-a-valid-choice'})
form.is_valid()  # True
like image 77
jproffitt Avatar answered Sep 16 '22 16:09

jproffitt