用WTForms和Flas预填充编辑表单

2024-06-28 20:13:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有以下代码:

用于编辑Post表单的类

class editPostForm(Form):
    postTitle = TextField('postTitle', validators.Required()])
    postSubtitle = TextField('postSubtitle', validators.Required()])

编辑帖子模板的路由

@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))

编辑帖子模板{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 %}

使用以下代码,我将在数据库中更新选定的文章,但是editpost模板没有显示数据库中已存在的值,并且所有字段都为空。

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


Tags: divformid数据库编辑errorpostclass
2条回答

我是一个n00b,但如果有帮助的话,我可以用python/jinja从SQL数据库中预先填充html输入和textarea字段,如下所示:

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"])

2。渲染模板(带有渲染模板功能)并传入相关变量(例如)

返回呈现模板(“edit.html”,name=name,about=about)

3。通过jinja将变量传递给html input/textarea元素。按如下方式传递到对象中的索引:

对于输入标记,使用如下的value属性:

    <input type="text" class="form-control" name="name" value="{{ name[0]["name"] }}">

对于textarea元素:

    <textarea class="form-control" name="about">{{ about[0]["about"] }}</textarea> 

可以按如下方式分别填充每个字段:

form = editPostForm(form)
form.postTitle.data = postTitle_from_database
form.postSubtitle.data = postSubtitle_from_database

或者可以使用process方法从给定对象填充表单字段:

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

Take form, object data, and keyword arg input and have the fields process them.

Parameters:

  • formdata – Used to pass data coming from the enduser, usually request.POST or equivalent.
  • obj – If formdata has no data for a field, the form will try to get it from the passed object.
  • **kwargs – If neither formdata or obj contains a value for a field, the form will assign the value of a matching keyword argument to the field, if provided.

Since BaseForm does not take its data at instantiation, you must call this to provide form data to the enclosed fields. Accessing the field’s data before calling process is not recommended.

相关问题 更多 >