如何在Django中测试一个具有表单的视图?

时间:2015-08-13 14:40:08

标签: javascript jquery django forms confirm

我正在Django中创建一个应用程序,我有一个视图,它接收来自html代码的表单,并在数据库中搜索是否存在模型中指定值的模型实例。

问题是我是Django的新手,我不知道如何测试视图的功能(即:如果视图的响应有一个值列表导致搜索请求中表单的值。)

这里我把我的观点的示例代码:

@login_required
def view(request):

# If it's a HTTP POST, we're interested in processing form data.
if request.method == 'POST':

    form = Form(data=request.POST)

    # If the form is valid
    if (form.is_valid()):

        resulting_of_search = ModelA.objects.filter(Q(att1=request.POST[attr1]) & ...)



    else:
        resulting_of_search = []


# Not a HTTP POST, so we render our form using two ModelForm instances.
# These forms will be blank, ready for user input.
else:
    form = Form()
    resulting_of_search= []



# Render the template depending on the context.
return render(request,
        'url/url.html',
        {'resulting':resulting_of_search} )

2 个答案:

答案 0 :(得分:0)

你试过Django Testing Tutorial吗?基本上,您只需要向视图发送帖子并测试响应是否会返回您期望的内容。

例如......

def test_index_view_with_no_questions(self):
    """
    If no questions exist, an appropriate message should be displayed.
    """
    response = self.client.get(reverse('polls:index'))
    self.assertEqual(response.status_code, 200)
    self.assertContains(response, "No polls are available.")
    self.assertQuerysetEqual(response.context['latest_question_list'], [])

取自文档。您想要更改最后一行,以便断言“结果”在上下文中。或者检查它是否包含您正在寻找的特定结果列表。像这样......

def test_results(self):
    response = self.client.get(reverse('ensaioak_bilatu'))
    self.assertQuerySetEqual(response.context['resulting'], [...whatever you expect resulting to contain...])

答案 1 :(得分:0)

通过阅读您的回答,我认为您不是在询问单元测试,而只是检查您的视图是否真正有效。首先,您可以使用以下链接在Django网站上提供的代码段:https://docs.djangoproject.com/en/1.8/topics/forms/#the-view