Django测试:AssertionError:形式'形式'不用于呈现响应

时间:2016-07-25 11:36:07

标签: python django forms testing

所以我正在编写测试以检查表单中是否出现验证错误。

这样做我收到以下错误:

======================================================================
FAIL: test_start_date_before_end_date_errors (reports.tests.ScheduleValidation)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/jwe/piesup2/reports/tests.py", line 61, in test_start_date_before_end_date_errors
    self.assertFormError(response, 'form', None, 'End Date Must Be Greater Than Start Date')
  File "/home/jwe/piesup2/venv/lib/python3.4/site-packages/django/test/testcases.py", line 467, in assertFormError
    " response" % form)
AssertionError: The form 'form' was not used to render the response

----------------------------------------------------------------------

clean()方法

中的models.py中引发了我专门检查的验证错误

class Schedule(models.Model)
    ... 
    ...

    def clean(self):
        if self.start_date and self.end_date:
            # Ensure that the end_date occurs after the start_date
            if self.end_date <= self.start_date:
                err = "End Date Must Be Greater Than Start Date"
                raise ValidationError(err)

我正在测试的Generic CreateView如下所示:

class ScheduleCreate(SuccessMessageMixin, FetchURLMixin, CreateView):
    model = Schedule
    form_class = ScheduleCreateForm
    template_name_suffix = '_create_form'

我能够将视图模板中的错误呈现为non_field_errors,如下所示:

{% for error in form.non_field_errors %}
    <label>{{ error }}</label>
{% endfor %}

我的测试如下:

class ScheduleValidation(RequiresLogin, TestCase):

    def setUp(self):
        self._client = client_fixture.create()[0]
        # Setup some example sample data for a Schedule
        self.data = {
            'client': self._client.id,
            'schedule_date': today,
            'billing_period': 'Q',
            'schedule_type': 'SE',

        }

    def test_start_date_before_end_date_errors(self):
        self.data['start_date'] = today
        self.data['end_date'] = yesterday
        response = self.client.post('reports:schedule-create', self.data, follow=True)
        # Check if redirects back to the page
        with self.assertTemplateUsed('schedule_create_form.html'):
            self.assertFormError(response, 'form', None, 'End Date Must Be Greater Than Start Date')

我设置了None的字段类型,以便访问non_field_errors,详见文档here

我已经尝试了

在我的视图模板中,我可以使用{{ form }}引用表单,包括任何non_field_errors。这意味着它正在正确地传递给模板。

我可以检查视图本身内的上下文数据。

def get_context_data(self, **kwargs):
    context = super(ScheduleCreate, self).get_context_data(**kwargs)
    assert False
    return context

从断点处我可以在浏览器中使用Werkzeug记录上下文变量的内容,这表明&#39;形式&#39;实际上是传递给模板

[console ready]
>>> context
{'form': <ScheduleCreateForm bound=True, valid=False, fields=(client;schedule_date;start_date;end_date;billing_period;schedule_type)>, 'view': <reports.views.ScheduleCreate object at 0x7f256eb6c908>}

这引出了一个问题,为什么我会收到此错误,我将如何解决此问题?

1 个答案:

答案 0 :(得分:2)

使用client.post()时,您应该使用实际的网址,而不是网址的名称。

您可以对其进行硬编码,例如:

response = self.client.post('/reports/schedules/create/, self.data, follow=True)

或者你可以撤销网址:

from django.core.urlresolvers import reverse
url = reverse('reports:schedule-create')
response = self.client.post(url, self.data, follow=True)