Al Bundy
Al Bundy

Reputation: 737

Django forms.ChoiceField without validation of selected value

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?

Upvotes: 17

Views: 13732

Answers (3)

jproffitt
jproffitt

Reputation: 6355

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

Upvotes: 27

radtek
radtek

Reputation: 36270

Best way to do this from the looks of it is create a forms.Charfield and use a forms.Select widget. Here is an example:

from django import forms

class PurchaserChoiceForm(forms.ModelForm):
    floor = forms.CharField(required=False, widget=forms.Select(choices=[]))

    class Meta:
        model = PurchaserChoice
        fields = ['model', ]

For some reason overwriting the validator alone did not do the trick for me.

Upvotes: 24

Samuele Mattiuzzo
Samuele Mattiuzzo

Reputation: 11038

As another option, you could write your own validator

from django.core.exceptions import ValidationError

def validate_all_choices(value):
    # here have your custom logic
    pass

and then in your form

class MyForm(forms.Form):
    my_field = forms.ChoiceField(validators=[validate_all_choices])

Edit: another option could be defining the field as a CharField but then render it manually in the template as a select with your choices. This way, it can accept everything without needing a custom validator

Upvotes: 2

Related Questions