如何用选择填充Django自定义multiplechoicefield

时间:2018-06-07 16:02:16

标签: python django django-forms

我有一个带有搜索框的表单,它使用jQuery填充multipleChoiceField。我需要使用自定义的multipleChoiceField,这样我就可以控制验证,只检查选择是否存在,而不是作为带有查询集的modelMultipleChoiceField的原始选择之一。但是,自定义multipleChoiceField在页面上呈现为空,直到您在搜索框中输入内容以通过jQuery填充选项。我希望它能够以一些选择来呈现。

class ArticleMultipleChoiceField(forms.MultipleChoiceField):
   def __init__(self, *args, **kwargs):
      super(ArticleMultipleChoiceField, self).__init__(*args, **kwargs)
      include_articles = [article.id for article in Article.objects.order_by('-sub_date')[:5]]
      self.choices = Article.objects.filter(id__in=include_articles).order_by('-sub_date')

在这种形式中,我收到错误“文章对象不可迭代”。我也尝试将self.choices更改为self.data,self.queryset和self.initial,在所有这三种情况下,我不断获得一个空的多选字段。

如何在此处使用查询集提供初始选择?

以下是用于的表格:

class StorylineAddArticleForm(forms.Form):
  articleSearchBox = forms.CharField(label="Search to narrow list below:")
  include_articles = [article.id for article in Article.objects.order_by('-sub_date')[:5]]
  articles = ArticleMultipleChoiceField()
  def __init__(self, *args, **kwargs):
    super(StorylineAddArticleForm, self).__init__(*args, **kwargs)
    self.fields['articleSearchBox'].required = False
    self.helper = FormHelper(self)
    self.helper.layout = Layout(
        Field('articleSearchBox'),
        Field('articles'),
        ButtonHolder(
            Submit('submit', 'Add', css_class='button white')
        )
        )

此外,这是由Crispy Forms提供的。

1 个答案:

答案 0 :(得分:1)

choices不接受QuerySet作为参数,它需要一个具有可接受值的二元组的列表或元组。请参阅choices此处的文档:https://docs.djangoproject.com/en/2.0/ref/models/fields/#field-choices

在这种情况下,您需要将Article查询集转换为上述格式的列表或元组。