Django测试客户端从查询中获取行id

时间:2014-09-17 08:01:58

标签: django django-tests

如何在下面的代码中打印响应中的id。用户确实存在于DB中。此外,我遇到了此错误。

from django.test import Client

c = Client(enforce_csrf_checks=False)
response = c.post('/reg/_user/', {'firstname': 'test', 'lastname' : '_test'})

观看get_user

def _user(request):
  try:
    response_dict = {}
    qd = request.POST
    firstname = qd.__getitem__('firstname')
    lastname = qd.__getitem__('lastname')
    up = UserProfile.objects.get(first_name=firstname,last_name=lastname)
    print up.id
    return up.id
  except:
    pass

错误:

 response = c.post('/reg/_user/', {'firstname': 'test', 'lastname' : '_test'})
 File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 483, in post
 response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
 File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 302, in post
 return self.request(**r)
 File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 444, in request
 six.reraise(*exc_info)
 File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 201, in get_response
response = middleware_method(request, response)
 File "/usr/local/lib/python2.7/dist-packages/django/middleware/clickjacking.py", line 30, in process_response
if response.get('X-Frame-Options', None) is not None:
AttributeError: 'UserProfile' object has no attribute 'get'

1 个答案:

答案 0 :(得分:1)

问题不在于您的测试,而在于视图本身。在Django中,视图总是必须返回HttpResponse object。有时这是通过使用像render()之类的快捷方式来实现的,但它又会返回一个HttpResponse对象。

如果由于某种原因你只想返回一个带有这个值的空页面,你可以改变

return up.id

return HttpResponse(up.id)

另外,我想知道:您是否仅为了测试UserProfile而创建视图而不将其用作实际网站上的视图?如果是这样,这段代码不属于视图,它应该放入unittest本身。您应该只使用测试客户端来测试实际的真实视图。


基本上不相关但非常重要的说明。这样:

try:
    # your view code
except:
    pass

是一个强大的反模式。你为什么要沉默所有潜在的问题?你真的应该停止这样做。