如何从WTForms表单自动生成完整的HTML [英] How to auto-generate full HTML from a WTForms form
问题描述
我正在尝试使用Jinja2模板为SQLAlchemy应用程序创建一个基于WTForms的简单管理界面.
I'm trying to create a simple WTForms-based admin interface for an SQLAlchemy app, using Jinja2 templates.
我已经阅读了WTForms-Alchemy的文档,了解它可以通过几行代码从我的模型自动生成表单,例如:
I've read the docs of WTForms-Alchemy and I understand that it can auto-generate a form from my model just via a few lines of code, like:
class UserForm(ModelForm):
class Meta:
model = User
我的问题是,即使我自动生成了此表单,也找不到任何有关如何将其转换为功能HTML页面的资源.有一些关于字段呈现错误的摘要,还有一些SO答案提到了用于呈现整个字段的宏,但是我发现关于如何自动生成完整的功能形式的资源绝对没有.
My problem is that even though I have this form auto-generated, I found no resource anywhere about how can I make it into a functional HTML page. There are a few snippets about rendering errors for fields, as well as some SO answers mentioning macros for rendering whole fields, but I found absolutely no resource about how to generate a full, functional form automatically.
//我知道这是Flask-Admin可能已经做的事情,因为我没有使用Flask,所以不幸的是这种可能性不大.
// I understand that this is something what Flask-Admin might do already, I'm not using Flask so this is not a possibility unfortunately.
推荐答案
WTForms让您自己决定将表单传递到模板后如何呈现表单.呈现表单的最简单方法是仅遍历表单并呈现字段.调用字段(或其标签)时,它会发出HTML.
WTForms leaves it up to you to figure out how to you want to render out your form after you pass it into your template. The simplest way to render a form would be to just iterate through your form and render the fields. When a field (or its label) is called, it emits HTML.
<form action="/some_url" method="POST">
{% for field in form %}
{{ field.label() }}
{{ field() }}
{% endfor %}
<button type="submit" />
</form>
此处提供的宏提供了一种自动生成围绕这些HTML的方法字段.
The macros provided here provide an automated way to generate HTML surrounding these fields.
这篇关于如何从WTForms表单自动生成完整的HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!