【问题标题】:ajax response a django form using HttpResponseajax 使用 HttpResponse 响应 django 表单
【发布时间】:2016-09-03 18:43:43
【问题描述】:

我的 ajax 函数有响应 django 形式。

in views.py code,
..
..
dictionary={'userform':userform,'info_form':info_form}
return HttpResponse(dictionary)

但是当我在 console.log 上发出警报时,响应类似于.. userforminfo_form。我无法在客户端 n 服务器端解析 json 类型。 如何 httpresponse 表单对象。当我尝试执行 json.dump 时,它给了我一个错误,即 json 对象不可序列化。 谢谢!

【问题讨论】:

  • 请创建一个minimal reproducible example 来演示该问题。不清楚你在问什么
  • 我只想在httpresponse中传递django表单..
  • 那么什么不起作用?您的代码目前在做什么?您的实际视图代码是什么? ajax与您的问题有什么关系? jquery与它有什么关系?还是json?
  • @Sayse 我只想让这两行运行 dictionary={'userform':userform,'info_form':info_form} return HttpResponse(dictionary) ...并且响应表单必须在客户端使用侧面...就像我们渲染了一个响应 django 表单。

标签: jquery json ajax django


【解决方案1】:

你可以使用from django.core import serializers,然后你可以解析来自数据库的数据,然后创建字典并将这个字典传递给HttpResponse

`userform = serializers.serialize('json', userform)`
`dictionary={'userform':userform}`
`HttpResponse(json.dumps(dictionary),content_type="application/json"`)

如果它不起作用,我们必须解析数据并从中创建列表,如下所示

array=[]
for a in data;
    array.append(a)
dictionary={'userform':array}
HttpResponse(json.dumps(dictionary),content_type="application/json")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-04
    • 2011-04-08
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多