我正在尝试instance
使用 ajax 从服务器渲染/获取表单字段,并希望在某个位置显示该字段,所以
视图.py
def edit_book_email(request, book_id):
book = Book.objects.get(id=book_id)
form = BookEmailForm(instance = book)
result = {
'email_field':form.fields['email'],
}
print result,">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
report_json = json.dumps(result, cls = DjangoJSONEncoder)
return HttpResponse(report_json, mimetype='application/json')
因此,从上面的代码中,我试图从表单中获取电子邮件字段并希望将其作为 json reposnse 发送,这样我就可以在需要的任何地方在模板中使用它
<html>
<head>
<script>
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
var form_field = '{{response.email_field}}'
$('.custom_design').html()
}
});
});
});
<script>
</head>
<div>
<span id="custom_design"><span>
</div>
</html>
但我面临以下错误
Traceback (most recent call last):
File "/home/user/Envs/app/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/user/app/apps/apps-web_nw/projsite/apps/website/views.py", line 665, in edit_book_email
report_json = json.dumps(result, cls = DjangoJSONEncoder)
File "/usr/lib/python2.7/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode
return _iterencode(o, 0)
File "/home/apps/Envs/apps/local/lib/python2.7/site-packages/django/core/serializers/json.py", line 103, in default
return super(DjangoJSONEncoder, self).default(o)
File "/usr/lib/python2.7/json/encoder.py", line 178, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <django.forms.fields.EmailField object at 0xb24a066c> is not JSON serializable
谁能告诉我如何避免此错误并在 html 上呈现电子邮件?