Django测试:从表单访问数据库返回空的lis

2024-10-02 10:33:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是Django表单,包含一个ChoiceField列表。这个列表内容是使用orm从表单中检索的。 它在应用程序中工作,但在测试中,实用程序方法返回空内容。 在创建表单之前,我查询同一个表作为实用工具方法,它返回3条记录。 知道实用程序方法为什么认为表是空的吗?在

1) 表格:

class JournalForm(forms.Form):
    journal_id = forms.CharField(widget=forms.HiddenInput(), required=False)
    journal_name = forms.CharField(label=ugettext('Journal name'), max_length=100, required=False)
    list_field = list()
    list_field.append(('0',ugettext('select')))
    list_field = list_field + getFieldOfInterestList()
    journal_fieldOfInterest = forms.ChoiceField(initial='0', choices = list_field, label=ugettext('Field of interest'), widget=forms.Select(), required=False)

2) 实用方法:

^{pr2}$

3) 测试:

@pytest.mark.django_db
def testJournals(self):
  # this query returns 3 fields, previously added in this test (so test database is not empty)
  print("nb fields = " + str(FieldOfInterest.objects.all().count()))
  journalForm = JournalForm(
          initial={
                'journal_name': 'Aquatic Botany',
                'journal_fieldOfInterest': 3,
  })  
  print("form = " + str(journalForm))
  # returns False
  print("is valid = " + str(journalForm.is_valid()))

打印的表单在选择中应该有更多选项,但只包含默认选项:

<tr><th><label for="id_journal_name">Journal name:</label></th><td><input id="id_journal_name" maxlength="100" name="journal_name" type="text" value="Aquatic Botany" /></td></tr>
<tr><th><label for="id_journal_fieldOfInterest">Field of interest:</label></th><td><select id="id_journal_fieldOfInterest" name="journal_fieldOfInterest">
<option value="0">select</option>
</select></td></tr>

谢谢你读我的书。在


Tags: 方法nameidfalse表单fieldformsselect

热门问题