0

以下のコードの応答から 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'
4

1 に答える 1

1

問題はテストではなく、ビュー自体にあります。Django では、ビューは常にHttpResponse オブジェクトを返す必要があります。これはrender()のようなショートカット関数を使用して達成されることもありますが、代わりに HttpResponse オブジェクトも返します。

何らかの理由で、この単一の値を持つ空のページを返したいだけの場合は、変更できます

return up.id

return HttpResponse(up.id)

また、テスト用にビューを作成UserProfileし、実際のサイトでビューとして使用しなかったのでしょうか。その場合、このコードはビューに属しておらず、単体テスト自体に配置する必要があります。テスト クライアントは、実際の実際のビューをテストする場合にのみ使用してください。


ほとんど無関係ですが、非常に重要な注意事項です。これ:

try:
    # your view code
except:
    pass

は強力なアンチパターンです。潜在的な問題をすべて黙らせたいと思うのはなぜですか。そんなことは本当にやめたほうがいいです。

于 2014-09-17T08:27:37.077 に答える