Python Flask-WTF - use same form template for add and edit operations

前端 未结 2 1057
一整个雨季
一整个雨季 2021-01-31 21:59

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 te

2条回答
  •  一个人的身影
    2021-01-31 22:21

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

    {# data.html #}
    
    {% block form %}
    

    {{ action }} {{ data_type }}

    {% render_form(form) %}
    {% endblock form %}

    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/")
    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. ...
    

提交回复
热议问题