Python Flask-WTF-使用相同的表单模板进行添加和编辑操作 [英] Python Flask-WTF - use same form template for add and edit operations

查看:229
本文介绍了Python Flask-WTF-使用相同的表单模板进行添加和编辑操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用Flask/Flask-WTF/SQLAlchemy,我看到的大多数示例CRUD代码都显示了用于添加/编辑的单独模板.似乎有两个模板具有几乎完全相同的html形式(例如books_add.html,books_edit.html).从概念上讲,对我来说更有意义的是拥有一个模板,例如"books_form.html",然后从两个单独的路由定义中对同一模板调用render_template.我不太确定如何完成此操作,例如:

I'm just getting started with Flask / Flask-WTF / SQLAlchemy, and most example CRUD code I see shows separate templates for adding / editing. It seems repetitive to have two templates with almost identical form html (e.g. books_add.html, books_edit.html). Conceptually it makes more sense to me to have one template, something like "books_form.html", and just call render_template on that same template from two separate route definitions. I'm not quite sure how to accomplish it though, something like:

@app.route('/books/add')
def add_book():
...
render_template('books_form.html', action = 'add')


@app.route('/books/edit/<id>')
def edit_book(id):
...
render_template('books_form.html', action = 'edit', id = id)

但是我不确定我是在正确的轨道上还是偏离最佳实践.感谢任何输入-有关如何处理单个模板文件以处理添加或编辑行为的特定想法.也欢迎链接到示例.

but I'm not sure if I'm on the right track, or deviating from best practice. Any input is appreciated - specific thoughts on how to handle the single template file to deal with either add or edit behavior. Links to examples are welcome as well.

谢谢!

推荐答案

甚至完全没有理由拥有单独的模板来添加/编辑不同种类的事物.考虑:

There is absolutely no reason to have separate templates for adding / editing different kinds of things even. Consider:

{# data.html #}
<!-- ... snip ... -->
{% block form %}
<section>
<h1>{{ action }} {{ data_type }}</h1>
<form action="{{ form_action }}" method="{{ method | d("POST") }}">
{% render_form(form) %}
</form>
</section>
{% endblock form %}

忽略宏render_form起作用(WTForms文档中有一个示例)-它只需要一个WTForms类型的对象并将表单呈现在无序列表中.然后,您可以执行以下操作:

Ignore the macro render_form works (there's an example one in WTForms' documentation) - it just takes a WTForms-type object and renders the form in an unordered list. You can then do this:

@app.route("/books/")
def add_book():
    form = BookForm()
    # ... snip ...
    return render_template("data.html", action="Add", data_type="a book", form=form)

@app.route("/books/<int:book_id>")
def edit_book(book_id):
    book = lookup_book_by_id(book_id)
    form = BookForm(obj=book)
    # ... snip ...
    return render_template("data.html", data_type=book.title, action="Edit", form=form)

但是您不必只局限于书籍:

But you don't need to limit yourself to just books:

@app.route("/a-resource/")
def add_resource():
    # ... snip ...
    return render_template("data.html", data_type="a resource" ...)

# ... etc. ...

这篇关于Python Flask-WTF-使用相同的表单模板进行添加和编辑操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆