如何将 json 传递给 render_to_response

我正在尝试通过 render_to_response 将一个 json 文件传递给前端。前端不是 django 模板,它是用 JS、HTML 等编码的。我遇到了一些奇怪的错误。任何人都可以帮助我。我附上了代码和回溯。


return render_to_response('ModelView.html', json.dumps(newDict))


Traceback (most recent call last):

  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 35, in inner

    response = get_response(request)

  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response

    response = self.process_exception_by_middleware(e, request)

  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response

    response = wrapped_callback(request, *callback_args, **callback_kwargs)

  File "C:\PythonWorkspace\ScApp\ScApp2\views.py", line 78, in ScorecardApp20

    return render_to_response('ModelView.html', json.dumps(newDict))

  File "C:\Users\kxc89\AppData\Local\Programs\Python\Python37\lib\site-packages\django\shortcuts.py", line 27, in render_to_response

    content = loader.render_to_string(template_name, context, using=using)

  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader.py", line 62, in render_to_string

    return template.render(context, request)

  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\backends\django.py", line 59, in render

    context = make_context(context, request, autoescape=self.backend.engine.autoescape)

  File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\context.py", line 274, in make_context

    raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__)

TypeError: context must be a dict rather than str.


aluckdog
浏览 282回答 2
2回答

慕婉清6462132

不要使用render_to_response,它已经过时了。使用render来代替。return render(request, 'ModelView.html', {'new_dict': json.dumps(newDict)})第三个参数必须是字典,因此您可以像我上面所做的那样将 json 字符串添加到字典中,或者您可能根本不想使用json.dumps()而只使用newDict.

千巷猫影

使用下面的代码import jsondata = open('/static/JsonFile.json').read() #opens the json file and saves the raw contentsJsonData = json.dumps(data) #converts to a json structurecontext = {'obj': JsonData}return render(request, 'templates', context)希望它应该工作!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python