python - WTForm在编辑模型时不会完全重新填充表单数据

  显示原文与译文双语对照的内容
0 0

编辑:类别字段现在可以重新填充。 在检索数据时出错。 App.py 已经被编辑。

我最近创建了一个"编辑帖子"窗体,用户点击一个链接,并将一些参数发送给函数。 我的函数搜索 post,WTForm模块尝试将表单重新填充来自目标文件的数据。 看起来 url url ( URLField ) 类别 ( SelectField ) 和名称( StringField ) 可以重新填充,但收费 details ( 文本栏) 字段显示的值不超过1. 谁可以指导我向右的direction,以重新填充一个瓶子 WTForm 。

这是我的尝试:

app.py


@app.route('/edit_post/<int:post_id>', methods=("GET","POST"))
@login_required
def edit_my_post(post_id):
 posts = models.Post.select().where(models.Post.id == post_id)
 if posts.count() == 0:
 abort(404)


 if post_user.id == current_user.id :
 post = models.Post.select().where(models.Post.id == post_id).get()
 form = forms.ProductForm(obj=post)

 if form.validate_on_submit():
 form.populate_obj(post)
 query = models.Post.update(user = post.user.id,
 name = form.name.data.strip(),
 content = form.details.data.strip(),
 url = form.url.data,
 category = = form.category.data
 ).where(models.Post.id == post_id)
 query.execute()
 flash("Your post has been edited.","success")
 return redirect(url_for('index'))
 else:
 flash("Ay! Stay away from that post!","warning")
 return redirect(url_for('index'))

 return render_template("edit.html",form=form)

models.py


class Post(Model):
 timestamp = DateTimeField(default=datetime.datetime.now)
 user = ForeignKeyField(
 rel_model = User,
 related_name = 'posts'
 )
 name = TextField()
 content = TextField()
 upvotes = IntegerField(default=0)
 url = TextField()
 category = TextField()

 class Meta:
 database = DATABASE
 order_by = ('-timestamp',)

Forms.py


class ProductForm(Form):
 name = StringField('Content Name', validators = [DataRequired()])
 url = URLField(validators=[url()])
 details = TextAreaField('Content Summary', validators = [DataRequired(),Length(max=140)])
 category = SelectField("Choose a category that your content fits in.", choices=CATEGORIES,coerce=int)

Edit.html


{% extends"layout.html" %}
{% from 'macros.html' import render_field %}

{% block content %}
<form method="POST" action="">
 {{ form.hidden_tag() }}
 {% for field in form %}
 {{ render_field(field) }}
 {% endfor %}
 <br>
 <button id="submit" type="submit">Edit Post</button>
</form>
{% endblock %}

注意:类别是字符串的( 长) array 。

时间: 原作者:

0 0

我通过简单地将细节ProductForm字段重命名为与Post表单中的属性相同的NAME 来修复这个问题。 因此,表单代码如下所示:


class ProductForm(Form):
 name = StringField('Content Name', validators = [DataRequired()])
 url = URLField(validators=[url()])
 content = TextAreaField('Content Summary', validators = [DataRequired(),Length(max=140)])
 category = SelectField("Choose a category that your content fits in.", choices=CATEGORIES,coerce=int)

然后我重命名了查询的部分,以检索这样的数据:


query = models.Post.update(user = post.user.id,
 name = form.name.data.strip(),
 content = form.content.data.strip(),
 url = form.url.data,
 category = form.category.data
 ).where(models.Post.id == post_id)
 query.execute()

原作者:
...