I'm using Select2 in my application for creating tags-like select dropdowns. Users can select number of predefined tags or create a new tag.
Relevant forms class part:
all_tags = Tag.objects.values_list('id', 'word')
# Tags
tags = forms.ChoiceField(
choices=all_tags,
widget=forms.Select(
attrs={
'class': 'question-tags',
'multiple': 'multiple',
}
)
)
The problem is that Django
won't allow custom tags(choices) upon validation. There error I'm getting looks like this: Select a valid choice. banana is not one of the available choices.
Is there any way around it?
Thanks
I would change the choicefield to charfield, and use the clean method to filter unwanted choices depending on certain conditions. Simply changing it to a char field with a select widget would work since Select2 is javascript anyways.
class Myform(forms.Form):
tags = forms.CharField(
max_length=254,
widget=forms.Select(
choices=tags, # here we set choices as part of the select widget
attrs={
'class': 'question-tags',
'multiple': 'multiple',
}
)
)
def clean_tags(self):
tags = self.cleaned_data['tags']
# more tag cleaning logic here
return tags
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With