【问题标题】:Allow dynamic choice in Django ChoiceField允许在 Django ChoiceField 中进行动态选择
【发布时间】:2015-06-14 02:40:14
【问题描述】:

我在我的应用程序中使用Select2 来创建类似标签的选择下拉菜单。用户可以选择预定义标签的数量或创建新标签。

相关表格类部分:

   all_tags = Tag.objects.values_list('id', 'word')

   # Tags
    tags = forms.ChoiceField(
        choices=all_tags,
        widget=forms.Select(
            attrs={
                'class': 'question-tags',
                'multiple': 'multiple',
            }
        )
    )

问题是Django 在验证时不允许自定义标签(选择)。我得到的错误如下所示:Select a valid choice. banana is not one of the available choices.

有什么办法吗?

谢谢

【问题讨论】:

  • 在标签创建时(提交前)发送 ajax 请求以保存新标签?
  • 您是否在使用django-select2(或使用 Select2 的众多 Django 应用程序之一)?
  • @skndstry 不确定这是否是最好的方法
  • @KevinBrown 我正在使用plang select2 和django。效果很好,唯一的问题是验证问题

标签: python django jquery-select2


【解决方案1】:

我会将choicefield 更改为charfield,并使用clean 方法根据特定条件过滤不需要的选择。只需将其更改为带有选择小部件的 char 字段即可,因为 Select2 无论如何都是 javascript。

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

【讨论】:

    猜你喜欢
    • 2010-11-26
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    相关资源
    最近更新 更多