使用flask和WTForms。我正在尝试将我的编辑和创建表单结合起来。当用户单击编辑时,视图会检查是否有传递的帖子ID,如果有,则抓取该帖子的当前信息并在模板中填充表单。我可以让它为每个字段工作,但'main_post'字段是单选按钮。
查看:
@app.route('/posts-update' , methods=['POST','GET'])
@login_required
def posts_update():
form = forms.Post()
if request.method == 'POST' and request.form['id']:
post = Post.query.filter_by(id=request.form['id']).first()
form.title.data = post.title
form.body.data = post.body
# Works for all but main_post
form.main_post.data = post.main_post
# Also tried this and it didn't work
# form = forms.Post(obj=post)
else:
post = False
# form = forms.Post()
return render_template('post_update.html', post=post, form=form)
形式:
#post create and update
class Post(Form):
title = StringField('Title', validators=[DataRequired()])
body = TextAreaField('Body', validators=[DataRequired()])
main_post = RadioField('Make Main Post', choices=[('1', 'yes'), ('0', 'no')], validators=[DataRequired()])
模板:
<input type="hidden" name="id" {% if post.id %}value="{{ post.id }}"{% endif %}>
{{ form.title.label }} : {{ form.title }} <br/>
{{ form.body.label }} : {{ form.body }} <br/>
{{ form.main_post.label }} : {{ form.main_post }} <br/>
<button class="button postfix" type="submit">{% if post == False %}Add{% else %}Update{% endif %}</button>
答案 0 :(得分:1)
在这里提出并回答了类似的问题How to dynamically set default value in WTForms RadioField?
您应该可以通过设置default
值然后运行form.process()
来执行此操作。
form.main_post.default = post.main_post
form.process()