这是请求网址:GET / api / v1 / companies / profile /?name = TestFirma 我是django的新手,这是我第一次尝试在django中传递带有GET请求的参数。
我已经使用名称(TestFirma)实际传递给get_object的记录器进行了测试。
我不明白为什么公司应该有get方法?我在这里误解了什么?
def get_object(request, name):
name = request.GET.get('name', '')
if name is not None:
company = Company.objects.get(name=name)
return company
堆栈:
[04/Jan/2016 13:40:49] "GET /static/templates/company/profile.html HTTP/1.1" 200 133
Internal Server Error: /api/v1/companies/profile/
Traceback (most recent call last):
File "C:\Users\Alexander\widewidewideass\lib\site-packages\django\core\handlers\base.py", line 223, in get_response
response = middleware_method(request, response)
File "C:\Users\Alexander\widewidewideass\lib\site-packages\django\middleware\clickjacking.py", line 31, in process_response
if response.get('X-Frame-Options', None) is not None:
AttributeError: 'Company' object has no attribute 'get'
Internal Server Error: /api/v1/companies/profile/
Traceback (most recent call last):
File "C:\Users\Alexander\widewidewideass\lib\site-packages\django\core\handlers\base.py", line 223, in get_response
response = middleware_method(request, response)
File "C:\Users\Alexander\widewidewideass\lib\site-packages\django\middleware\clickjacking.py", line 31, in process_response
if response.get('X-Frame-Options', None) is not None:
AttributeError: 'Company' object has no attribute 'get'
[04/Jan/2016 13:40:49] "GET /api/v1/companies/profile/?name=TestFirma HTTP/1.1" 500 75282
[04/Jan/2016 13:40:49] "GET /favicon.ico HTTP/1.1" 200 6524
答案 0 :(得分:2)
我假设您要返回Company
对象的JSON响应。如果这是您想要的,那么您应该序列化该对象,然后将其作为HttpResponse
对象返回。
import json
from django.http import HttpResponse
from django.core import serializers
def get_object(request, name):
name = request.GET.get('name', '')
if name is not None:
obj = Company.objects.get(name=name)
company = serializers.serialize('json', [obj,])
struct = json.loads(company)
data = json.dumps(struct[0])
return HttpResponse(data, content_type='json')