【问题标题】:Django testing: AssertionError: The form 'form' was not used to render the responseDjango 测试:AssertionError:表单“form”未用于呈现响应
【发布时间】:2016-07-25 11:36:07
【问题描述】:

所以我正在编写一个测试来检查我的表单中是否发生了验证错误。

这样做我收到以下错误:

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

我正在测试的通用 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 记录上下文变量的内容,这表明“表单”实际上已传递给模板

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

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

【问题讨论】:

    标签: python django forms testing


    【解决方案1】:

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

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

    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)
    

    【讨论】:

      猜你喜欢
      • 2022-07-18
      • 2016-06-02
      • 1970-01-01
      • 2015-12-20
      • 2017-05-26
      • 2018-06-18
      • 1970-01-01
      • 2012-12-27
      • 2019-09-07
      相关资源
      最近更新 更多