Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow dynamic choice in Django ChoiceField

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

like image 703
intelis Avatar asked Apr 08 '15 22:04

intelis


1 Answers

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
like image 83
Mikeec3 Avatar answered Oct 01 '22 19:10

Mikeec3