【问题标题】:Prepopulate WTForms radio field with info from view使用视图中的信息预填充 WTForms 单选字段
【发布时间】:2017-01-31 02:53:35
【问题描述】:

使用烧瓶和 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>

【问题讨论】:

    标签: python flask wtforms flask-wtforms


    【解决方案1】:

    How to dynamically set default value in WTForms RadioField?How to dynamically set default value in WTForms RadioField?

    您应该能够通过设置default 值然后运行form.process() 来做到这一点。

    form.main_post.default = post.main_post
    form.process()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 2017-05-05
      • 2011-07-04
      • 2013-11-03
      • 2020-05-08
      • 1970-01-01
      相关资源
      最近更新 更多