【问题标题】:Django test client get row id from queryDjango 测试客户端从查询中获取行 ID
【发布时间】:2014-09-17 08:01:58
【问题描述】:

如何在下面的代码中从响应中打印 id。用户确实存在于数据库中。我也遇到了这个错误。

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'

【问题讨论】:

    标签: django django-tests


    【解决方案1】:

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

    如果出于某种原因您只想返回一个包含该单一值的空页面,您可以更改

    return up.id
    

    return HttpResponse(up.id)
    

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


    关于一个几乎不相关但非常重要的说明。这个:

    try:
        # your view code
    except:
        pass
    

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

    【讨论】:

    • 还有一件小事:qd.__getitem__('firstname')qd['firstname'] 的同义词,但前者更短更清晰 :)
    • 还有qd.get('firstname'),如果item不存在不会抛出异常(而是返回None)。
    • 很遗憾,我不明白你的问题。你能改写一下吗?
    • 我想在我的测试文件的一个变量中获取 id。我该怎么做
    • 使用response.content,但您是否在测试之外使用视图?如果不将视图代码移动到测试本身,它看起来不像您需要的是视图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多