[英]How can I test in Django a view which has a form?
I am creating an application in Django and I have a view which receives a form from the html code, and searches in the database if there are any instances of a model whit the values specified in the form. 我正在Django中创建一个应用程序,我有一个视图,该视图从html代码接收一个表单,并在数据库中搜索是否有模型的任何实例以及该表单中指定的值。
The problem is that I am new in Django and I don't really know how can I test the functionality of the view (ie: if the view's response has a list of values resulting the search of the values of the form in the request). 问题是我是Django的新手,我真的不知道如何测试视图的功能(即:如果视图的响应中包含值列表,从而导致在请求中搜索表单的值) 。
Here I put the example code of my view: 在这里,我放置了我的视图的示例代码:
@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} )
Have you tried the Django Testing Tutorial ? 您是否尝试过Django Testing Tutorial ? Essentially, you just need to send a post to your view and test that the response returns what you'd expect.
本质上,您只需要向视图发送帖子并测试响应是否返回了您期望的结果。
For example.. 例如..
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'], [])
Taken from the docs. 取自文档。 You'd want to change that last line so that you assert that 'resulting' is in the context.
您需要更改最后一行,以便断言“结果”在上下文中。 Or check that it contains a specific list of results you're looking for.
或检查它是否包含您要查找的结果的特定列表。 Like this..
像这样..
def test_results(self):
response = self.client.get(reverse('ensaioak_bilatu'))
self.assertQuerySetEqual(response.context['resulting'], [...whatever you expect resulting to contain...])
From reading your answer, I think you are not asking about unit testing but just checking whether your view actually works . 通过阅读您的答案,我认为您不是在询问单元测试,而只是在检查您的视图是否确实有效 。 As a start, you can use the code snippet provided on the Django website at the following link: https://docs.djangoproject.com/en/1.8/topics/forms/#the-view .
首先,您可以使用以下链接在Django网站上提供的代码段: https : //docs.djangoproject.com/en/1.8/topics/forms/#the-view 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.