Allow dynamic choice in Django ChoiceField

人盡茶涼 提交于 2019-12-10 15:59:46

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/29526511/allow-dynamic-choice-in-django-choicefield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!