使用WTForms和Flask预填充编辑表单

Eri*_*ric 6 python jinja2 flask flask-wtforms flask-bootstrap

我可以使用WTForms和Flask向我的数据库添加一个新条目,我也可以编辑,问题是我需要以编辑形式显示数据库中已有的信息.

我有以下代码:

编辑帖子表格的类

class editPostForm(Form):
    postTitle = TextField('postTitle', validators.Required()])
    postSubtitle = TextField('postSubtitle', validators.Required()])
Run Code Online (Sandbox Code Playgroud)

编辑帖子模板的路径

@app.route('/editpost/<postId>', methods = ['GET','POST'])
def editpost_page(postId):
try:
    form = editPostForm(form)

    if request.method == "POST" and form.validate():
        postTitle = form.postTitle.data
        postSubtitle = form.postSubtitle.data

        c, conn = connection()

        query = c.execute("SELECT * FROM posts WHERE post_id = (%s)",
                          [noinjection(postId)])

        c.execute("UPDATE posts SET post_title=%s, post_subtitle=%s WHERE post_id = %s",
                     [
                     noinjection(postTitle),
                     noinjection(postSubtitle),
                     noinjection(postId)
                     ])

        conn.commit()

        flash("Post Edited", 'success')

        c.close()
        conn.close()
        gc.collect()

        return redirect(url_for('posts'))

    return render_template("editpost.html", form = form, POST_ID = postId)

except Exception as e:
    return(str(e))
Run Code Online (Sandbox Code Playgroud)

编辑帖子模板{jinja}

{% extends "header.html" %}

{% block body %}

<body>
    <div class="container-fluid">
        <br />
        <h4>Edit Post</h4>
        <br />
        {% from "_formhelpers.html" import render_field %}
        <form action="/editpost/{{ POST_ID }}" class="form-horizontal" method="post">
            {% from "_formhelpers.html" import render_field %}
            <form action="/editpost/" method="post">
              <div class="form-group">
                <label for="postTitle">Post Title</label>
                <input type="text" class="form-control" id="postTitle" name="postTitle" placeholder="Post Title" value="{{request.form.postTitle}}">
              </div>
              <div class="form-group">
                <label for="postSubtitle">Post Subtitle</label>
                <input type="text" class="form-control" id="postSubtitle" name="postSubtitle" placeholder="Post Subtitle" value="{{request.form.postSubtitle}}">
              </div>
              <button type="submit" class="btn btn-default">Submit</button>
            </form>
            {% if error %}
                <p class="error"><strong>Error: </strong>{{error}}</p>
            {% endif %}
        </form>
        {% if error %}
            <p class="error"><strong>Error: </strong>{{error}}</p>
        {% endif %}

    </div>
</body>

{% endblock %}
Run Code Online (Sandbox Code Playgroud)

使用以下代码,我将在数据库中获取要更新的选定帖子,但editpost模板未显示已存在于数据库中的值,并且所有字段均为空白.

如何在编辑之前预先填充表单?

kch*_*ski 12

您可以单独填充每个字段,如下所示:

form = editPostForm(form)
form.postTitle.data = postTitle_from_database
form.postSubtitle.data = postSubtitle_from_database
Run Code Online (Sandbox Code Playgroud)

或者您可以使用process方法填充给定对象的表单域:

process(formdata=None, obj=None, **kwargs)

获取表单,对象数据和关键字arg输入,并使字段处理它们.

参数:

  • formdata - 用于传递来自最终用户的数据,通常是request.POST或等效的.
  • obj - 如果formdata没有字段的数据,表单将尝试从传递的对象中获取它.
  • **kwargs - 如果formdata或obj都不包含字段的值,则表单将为字段分配匹配关键字参数的值(如果提供).

由于BaseForm在实例化时不会获取其数据,因此必须调用此方法以向封闭的字段提供表单数据.建议不要在调用进程之前访问字段的数据.


小智 6

我能够使用 Python 和 Jinja 从 SQL 数据库中预填充 HTMLinputtextarea字段,如下所示:

1. 将数据库中的相关数据存储在一个变量中:

    name = db.execute("""SELECT name FROM users WHERE id = :id""", id=session["user_id"])

    about = db.execute("""SELECT about FROM users WHERE id = :id""", id=session["user_id"])
Run Code Online (Sandbox Code Playgroud)

2.渲染模板(带有render_template函数)并传入相关变量:

return render_template("edit.html", name = name, about = about)

3.通过jinja将变量传递给htmlinputtextarea元素。已传递的对象的索引如下:

对于input标签,使用 value 属性如下:

    <input type="text" class="form-control" name="name" value="{{ name[0]["name"] }}">
Run Code Online (Sandbox Code Playgroud)

对于textarea元素:

    <textarea class="form-control" name="about">{{ about[0]["about"] }}</textarea> 
Run Code Online (Sandbox Code Playgroud)