如何将django表单呈现为html(不在模板中) [英] How to render django form into html (not in template)
问题描述
我有一个模板在其中
<div id="form-wrapper">
{{form}}
</div>
现在,如果用户提交(通过 AJAX
)并且出现错误,我想做
Now if the user submits (via AJAX
) and there are errors, I want to do
$(#form-wrapper").html(data.form);
基本上只需替换整个表单即可显示错误.但是当我写
Basically just replace the whole form to show the errors. But when I write
返回JsonResponse({'form':form})
告诉我我的表单不可序列化.说得通.所以我的问题是:django如何将表单呈现为html?我应该调用什么功能?
in the view django tells me that my form isn't serializable. Makes sense. So my question is: how does django render forms into html? What function should I call?
注意:我知道我可以只返回错误而不是整个表单,但这需要在模板中添加更多js代码才能将每个字段的错误放在正确的位置.我想要django在说 {{form}}
时使用的一个功能.
Note: I know I can return just the errors instead of the whole form, but that would require more js code in the template to put each field's errors in the correct place. I want the one function that django uses when I say {{form}}
.
谢谢!
推荐答案
在与任何对象一起显示时,所有模板所做的全部操作称为 str()
(或 unicode()
) 在上面.在内部,在form类上实现这些方法的方法仅委托给 as_table()
方法.因此,您可以直接致电:
All the template does when presented with any object is call str()
(or unicode()
) on it. Internally, the methods that implement those on the form class simply delegate to the as_table()
method. So you can just call that directly:
return JsonResponse({'form': form.as_table()})
但是请注意,您可能想添加其他HTML,在这种情况下,更好的方法可能是使用 render_to_string
将一个简单的模板片段(包括表单)简单呈现为字符串-并在Json响应中发送.
Note, though, that you might want to add other HTML, in which case a better approach might be to simply render a short template snippet, including the form, to a string - using render_to_string
- and send that in the Json response.
这篇关于如何将django表单呈现为html(不在模板中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!