Python Django: How To Override Validation On Multiplechoicefield
I'm trying to save multiple checkbox selections on a Charfield, but I cannot bypass the message: Select a valid choice. ['...', '...', '...'] is not one of the available choices
Solution 1:
In your models - you're using...
sinais_e_sintomas_locais = models.CharField(
blank=False, choices=TIPOS_SINAIS_E_SINTOMAS, max_length=255,
verbose_name="Sinais e Sintomas locais (marque todas as opções \
válidas) *",
)
... and have choices=TIPOS_SINAIS_E_SINTOMAS
which'll work in the event of only a single selection, but where you try to pipe delimit multiple selections, they'll fail to match and cause the validation error.
Answer : remove the choices=
option. Although - you should check that all values are valid choices in your clean_<field>
methods before pipe delimiting them and saving it as a CharField
, eg:
defclean_sinais_e_sintomas_locais(self):
ssl = self.cleaned_data['sinais_e_sintomas_locais']
# Check there are no selections or only valid selectionsifnot (ssl orset(ssl).difference(TIPOS_SINAIS_E_SINTOMAS)):
self.cleaned_data['sinais_e_sintomas_locais'] = '|'.join(ssl)
return self.cleaned_data['sinais_e_sintomas_locais']
# Error: some individual values weren't valid...raise forms.ValidationError('some message')
Post a Comment for "Python Django: How To Override Validation On Multiplechoicefield"