django test:从表单访问数据库返回空列表

时间:2017-08-06 18:40:16

标签: python django pytest

我正在使用包含ChoiceField列表的Django表单。使用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)实用方法:

def getFieldOfInterestList():
    try:
        interest_list = list()
        for field in FieldOfInterest.objects.all().order_by('name'):
            interest_list.append((str(field.id_field),field.name))
        return interest_list     
    except Exception as ex:
        print("an error in getFieldOfInterestList() : " + str(ex))
        return list()

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()))

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

<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>

感谢您阅读我。

0 个答案:

没有答案