【问题标题】:django unit test for ModelChoiceField form with CheckboxSelectMultiple widget带有 CheckboxSelectMultiple 小部件的 ModelChoiceField 表单的 django 单元测试
【发布时间】:2017-01-03 08:00:13
【问题描述】:

我有一个表格

class TypesForm(forms.Form):
  ....    
  types = forms.ModelChoiceField(
  label='Types',
  queryset=models.Type.objects.all(),
  widget=forms.CheckboxSelectMultiple)
  ...

当我想测试多个选中的框时,如何为此表单编写单元测试?

对于一个字段的检查工作如下:

form = forms.TypesForm({'types': 1})
self.assertTrue(form.is_valid())

但是我尝试设置两个选中的复选框,都会导致错误:

{'types': [u'Select a valid choice. That choice is not one of the available choices.']}

我试过了,但这些不起作用。例如。 :

form = forms.TypesForm({'types': [1, 2]})

form = forms.TypesForm({'types': (1, 2)})

和其他选项..

对于 forms.ModelForm,列表 [1, 2] 有效,因此需要一种方法。

【问题讨论】:

    标签: django django-forms django-admin django-views


    【解决方案1】:

    ModelChoiceField 允许您选择一个单个 对象。如果要允许选择多个对象,请使用ModelMultipleChoiceField

    在您的单元测试中,为该字段传递一个 id 列表,例如:

    form = forms.TypesForm({'types': [1, 2]})
    

    【讨论】:

      猜你喜欢
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      • 2017-10-19
      • 2010-10-11
      相关资源
      最近更新 更多