当我尝试在Django中测试表单验证时,收到此错误消息。
AssertionError: The form 'form' was not used to render the response
我正在尝试围绕FileUpload表单测试一些东西。
奇怪的是,只有一个测试失败,在使用该表单的一堆中。例如,下面的第一个和第二个测试几乎相同,但第一个测试成功,第二个测试返回AssertionError
。
第一个和第二个之间的唯一区别是文件路径和字段属性。我无法将问题缩小到这两个项目。
def test_invalid_file_extension_error(self):
date = dt(2018,1,14)
with open(bad_path) as fp:
data = {
'account': self.account.pk,
'date': self.date.strftime("%d-%m-%Y"),
'file': fp
}
response = self.client.post(reverse('saveskore:upload-savings'), data, follow=True)
field = 'file'
self.assertEqual(response.status_code, 200)
self.assertFormError(response, 'form', field, u'Unsupported file extension.')
def test_invalid_due_to_future_date(self):
date = dt(2020,1,1)
with open(good_path) as fp:
data = {
'account': self.account.pk,
'date': self.date.strftime("%d-%m-%Y"),
'file': fp
}
response = self.client.post(reverse('saveskore:upload-savings'), data, follow=True)
field = 'date'
self.assertEqual(response.status_code, 200)
self.assertFormError(response, 'form', field, u'The date cannot be a future date!')
以下是我的观点:
class UploadView(CreateView):
model = SaveReports
form_class = SaveReportsForm
def form_valid(self, form):
report = form.save()
account = ReportsToTraxns(
account = report.account.name,
filename = report.file.name
)
account.commit_statement(report.account_id)
return super().form_valid(form)
这是我的表格:
class SaveReportsForm(ModelForm):
date = DateField(widget=DateInput(format = '%d-%m-%Y'),
input_formats=['%d-%m-%Y',]
)
class Meta:
model = SaveReports
exclude = ['datetime_upload']
def __init__(self, *args, **kwargs):
super(SaveReportsForm, self).__init__(*args, **kwargs)
self.fields['account'].empty_label = None
def clean_date(self):
date = self.cleaned_data['date']
if date > dt_date.today():
raise ValidationError("The date cannot be a future date! ... unless you own a time machine")
return date
我感谢任何有帮助的人!
修改
它似乎与文件路径有关。如果我在上面的第二个测试中用good_path
替换bad_path
,问题就会消失。这是文件路径。
good_path = '/vagrant/app/save/tests/reports/bank (4).csv'
bad_path = '/vagrant/app/save/tests/reports/test.txt'