我有一个与 Flask WTForm 复选框相关的问题

问题描述 投票:0回答:1

我有一个博客页面,我想让人们匿名回复帖子。因此,如果人们选中该复选框,我希望属性“is_anonymous”变为 True。但我收到以下错误。我做错了什么?

werkzeug.exceptions.BadRequestKeyError:400 错误请求:浏览器(或代理)发送了该服务器无法理解的请求。 关键错误:'is_anonymous'

这是我的路线

@app.route('/add_reply/<int:post_id>', methods = ['GET','POST'])
def add_reply(post_id):
    form = PostForm()
    post = Posts.query.get_or_404(post_id)
    if request.method == 'POST':
        reply = Replies(comment_id=post_id, content=request.form['content'], author_id=current_user.id, is_anonymous=request.form['is_anonymous'])
        form.content.data = ""
        form.is_anonymous.data = False
        # Add reply to database
        try:
            db.session.add(reply)
            db.session.commit()
            flash("Success")
            replies = Replies.query.order_by(Replies.date_replied)
            return render_template("posts.html", replies = replies)
        except:
            db.session.rollback()
            flash("Error")
            return redirect(url_for('posts'))
    return render_template("add_reply.html", form = form, post = post)

这是我的 HTML 页面

{% for message in get_flashed_messages() %}                                                             
<div class="alert alert-success alert-dismissible fade show" role="alert">
    {{message}}
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
  </div>
{% endfor %}

{% if current_user.is_authenticated %}

    <div class="shadow-sm p-3 mb-5 bg-body-tertiary rounded bg-white">
        <h4>{{post.title}} </h4>
        <small>By: {% if post.is_anonymous %} Anonymous {% else %} {{post.author.name}} {% endif %} <br/>
        {{post.date_posted}}</small><br/><br/>
        {{post.content | safe}}
    </div>

    <div class="shadow-sm p-3 mb-5 bg-body-tertiary rounded bg-white">                                      
        <form method="POST">
            {{ form.hidden_tag() }}                                                                     
            
            {{ form.content.label(class="form-label") }}                                                
            {{ form.content(class="form-control", rows = "5") }}                                        
            <br>
            {{ form.is_anonymous.label(class="form-label") }}                                    
            {{ form.is_anonymous(class="form-check-input") }}                                                                        
            <br/><br/>
            {{ form.submit(class="btn btn-secondary") }}                                                                                                     
        </form>
        {{ ckeditor.load() }}                                                                             
        {{ ckeditor.config(name='body') }}
    </div>
{% else %}
    <br/>
    <h5>Please, login</h5><br/>
    <a href = "{{url_for('login')}}" class = "btn btn-outline-secondary btn-sm">login</a>
{% endif %}

表格

class PostForm(FlaskForm):
    title = StringField("Title", validators = [DataRequired()])
    content = CKEditorField('Content', validators = [DataRequired()])
    author = StringField("Author")
    is_anonymous = BooleanField('share as anonymous')
    submit = SubmitField("Share")

数据库模型

class Replies(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    comment_id = db.Column(db.Integer, db.ForeignKey('posts.id'), nullable = False)
    content = db.Column(db.Text)
    date_replied = db.Column(db.DateTime, default = datetime.datetime.now(datetime.UTC))
    author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    is_anonymous = db.Column(db.Boolean, default = False)
flask checkbox
1个回答
0
投票

KeyError 表示该键不是字典的一部分

request.form
。这是因为如果未设置该复选框,则不会传输键值对。您可以使用
form.is_anonymous.data
获取输入来解决该错误。

from flask import (
    Flask, 
    redirect, 
    render_template_string, 
    request, 
    url_for
)
from flask_wtf import FlaskForm
from wtforms import BooleanField

app = Flask(__name__)
app.secret_key = 'your secret here'

class MyForm(FlaskForm):
    is_anonymous = BooleanField()

@app.route('/', methods=['GET', 'POST'])
def index():
    form = MyForm(request.form)
    if form.validate_on_submit():
        print(form.is_anonymous.data)
        return redirect(url_for('index'))
    return render_template_string(
        '''
            <form method="post">
                {{ form.hidden_tag() }}
                <div>
                    {{ form.is_anonymous.label() }}
                    {{ form.is_anonymous() }}
                </div>
                <button type="submit">Submit</button>
            </form>
        ''', 
        **locals()
    )

顺便说一句,我注意到您已经指定了输入字段的验证,但从未使用

form.validate_on_submit()
form.validate()
运行它。我觉得这不是故意的。

© www.soinside.com 2019 - 2024. All rights reserved.