26👍
✅
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
22👍
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.
- Django GROUP BY field value
- Create UUID on client and save primary key with Django REST Framework and using a POST
- Django attribute error. 'module' object has no attribute 'rindex'
- Save Django Foreign Key
1👍
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
Source:stackexchange.com