我正在尝试使用ajax从服务器渲染/获取instance
表单字段,并希望将该字段显示在某处,所以
views.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')
所以从上面的代码中,我试图从表单中获取emailfield并希望将其作为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上呈现电子邮件吗?
答案 0 :(得分:0)
如果你想要字段的html,你需要像这样渲染BoundField
:
result = {
'email_field': str(form['email']),
}
有点不清楚你在javascript中想要做什么。如果您的html是django模板,那么这一行将成为一个问题:
var form_field = '{{response.email_field}}'
仅当response
传递给模板上下文时才会起作用。否则,你不能在javascript中使用django标签。如果您只想获取在ajax视图中返回的字段的html,请执行以下操作:
var form_field = response.email_field;