我正在尝试使用Geodjango中的用户位置创建Google地图API 3标记。
我在渲染Google地图和标记时遇到Internal Server Error 500
。在CMD控制台上,我得到TypeError: 'GeoQuerySet' object is not callable
。
您能否提出解决方案并解释异常原因?
views.py
class MyView(View):
def get(self, request):
resp = UserList.objects.all().values('nickname', 'last_location')
print (resp)
return JsonResponse(request, resp, safe=False)
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from mymap_app import views as map_views
admin.autodiscover()
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^my_endpoint/$',map_views.MyView.as_view(),name='user_list'),
url(r'^$',map_views.IndexView.as_view(), name='index'),
]
回溯:
Traceback (most recent call last):
File "C:\Python35-32\lib\site-packages\django\core\handlers\exception.py", lin
e 41, in inner
response = get_response(request)
File "C:\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187
, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185
, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python35-32\lib\site-packages\django\views\generic\base.py", line 68,
in view
return self.dispatch(request, *args, **kwargs)
File "C:\Python35-32\lib\site-packages\django\views\generic\base.py", line 88,
in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\Kaleab\Desktop\WebMap\AAmap_Project\mymap_app\views.py", line 2
1, in get
return JsonResponse(request, resp, safe=False)
File "C:\Python35-32\lib\site-packages\django\http\response.py", line 530, in
__init__
data = json.dumps(data, cls=encoder, **json_dumps_params)
File "C:\Python35-32\lib\json\__init__.py", line 237, in dumps
**kw).encode(obj)
TypeError: 'GeoQuerySet' object is not callable
[05/Sep/2017 22:36:45] "GET /my_endpoint/ HTTP/1.1" 500 18865
答案 0 :(得分:0)
看看这个:data = json.dumps(data, cls=encoder, **json_dumps_params)
。
JsonResponse正在尝试序列化您传递的参数,但是GeoQuerySet不能通过函数调用进行序列化,因此会引发TypeError。请参阅以下文档: https://docs.python.org/2/library/json.html
如果skipkeys为true(默认值:False),则字典键不是a 基本类型(str,unicode,int,long,float,bool,None)将是 跳过而不是引发TypeError。
为了解决这个问题,你可以改为:
return HttpResponse(
json.dumps(response, skipkeys=True), content_type="application/json"
)
也可以将GeoQuerySet格式化为python字典,然后将其传递给JsonResponse。
答案 1 :(得分:0)
对views.py的以下更改解决了Geoqueryset object not callable
错误。
class MyView(View):
def get(self, request):
response = UserList.objects.all().values('nickname','last_location')
print(response)
return JsonResponse({'response':list(response)})