英文:
SelectField Not Returning Boolean Value for DB
问题
我有点疯狂。我无法弄清楚如何使用SQLAlchemy将布尔值传输到我的数据库。我尝试了BooleanField和SelectField两种方法。它一直返回空值。请帮忙。
在我的数据库中显示的是1或0,表示True和False。然后我从数据库中取这些值并在我的网页上显示它们。
Python
with app.app_context():
    class Cafe(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(250), unique=True, nullable=False)
        map_url = db.Column(db.String(500), nullable=False)
        img_url = db.Column(db.String(500), nullable=False)
        location = db.Column(db.String(250), nullable=False)
        seats = db.Column(db.String(250), nullable=False)
        has_toilet = db.Column(db.Boolean, nullable=False)
        has_wifi = db.Column(db.Boolean, nullable=False)
        has_sockets = db.Column(db.Boolean, nullable=False)
        can_take_calls = db.Column(db.Boolean, nullable=False)
        coffee_price = db.Column(db.String(250), nullable=True)
        db.session.commit()
class NewCafe(FlaskForm):
    name = StringField("Cafe Name", validators=[DataRequired()])
    map_url = StringField("Map URL", validators=[DataRequired(), URL()])
    img_url = StringField("Image URL", validators=[DataRequired(), URL()])
    location = StringField("Address", validators=[DataRequired()])
    coffee_price = StringField("Average Price", validators=[DataRequired()])
    seats = StringField("Seats?", validators=[DataRequired()])
    has_toilet = SelectField("Toilet? ", choices=[('', 'No'), (True, 'Yes')], coerce=bool)
    has_wifi = SelectField("WiFi? ", choices=[('', 'No'), (True, 'Yes')], coerce=bool)
    has_sockets = SelectField("Sockets? ", choices=[('', 'No'), (True, 'Yes')], coerce=bool)
    can_take_calls = SelectField("Take Calls? ", choices=[('', 'No'), (True, 'Yes')], coerce=bool)
    submit = SubmitField("Submit Post")
@app.route("/new-post", methods=["GET", "POST"])
def new_post():
    form = NewCafe(active=True)
    if request.method == 'POST':
        new_post = Cafe(
            name=request.form.get('name'),
            map_url=request.form.get('map_url'),
            location=request.form.get('location'),
            img_url=request.form.get('img_url'),
            has_sockets=bool(request.form.get("sockets")),
            has_toilet=bool(request.form.get("toilet")),
            has_wifi=bool(request.form.get("wifi")),
            can_take_calls=bool(request.form.get("calls")),
            coffee_price=request.form.get("coffee_price"),
            seats=request.form.get("seats"),
        )
        db.session.add(new_post)
        db.session.commit()
        return redirect(url_for('get_all_posts'))
    return render_template("make-post.html", form=form)
HTML:这是我调用表单的地方
<div class="container">
    <div class="row">
        <div class="col-lg-8 col-md-10 mx-auto">
            {{ ckeditor.load() }}
            {{ ckeditor.config(name='body') }}
            {{ wtf.quick_form(form, novalidate=True, button_map={"submit": "primary"}) }}
        </div>
    </div>
</div>
英文:
I'm going a bit crazy here. I can not not figure out how to get a Boolean value transferred to my DB using SQLAlchemy. I've tried both BooleanField and SelectField. It keeps returning a null value Please help.
What it shows in my DB is either a 1 or 0 to represent True and False. I then take those values from the DB and display them on my webpage
Python
with app.app_context():
class Cafe(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(250), unique=True, nullable=False)
map_url = db.Column(db.String(500), nullable=False)
img_url = db.Column(db.String(500), nullable=False)
location = db.Column(db.String(250), nullable=False)
seats = db.Column(db.String(250), nullable=False)
has_toilet = db.Column(db.Boolean, nullable=False)
has_wifi = db.Column(db.Boolean, nullable=False)
has_sockets = db.Column(db.Boolean, nullable=False)
can_take_calls = db.Column(db.Boolean, nullable=False)
coffee_price = db.Column(db.String(250), nullable=True)
db.session.commit()
class NewCafe(FlaskForm):
name = StringField("Cafe Name", validators=[DataRequired()])
map_url = StringField("Map URL", validators=[DataRequired(), URL()])
img_url = StringField("Image URL", validators=[DataRequired(), URL()])
location = StringField("Address", validators=[DataRequired()])
coffee_price = StringField("Average Price", validators=[DataRequired()])
seats = StringField("Seats?", validators=[DataRequired()])
has_toilet = SelectField("Toilet? ", choices=[('', 'No'), (True, 'Yes')], coerce=bool)
has_wifi = SelectField("WiFi? ", choices=[('', 'No'), (True, 'Yes')], coerce=bool)
has_sockets = SelectField("Sockets? ", choices=[('', 'No'), (True, 'Yes')], coerce=bool)
can_take_calls = SelectField("Take Calls? ", choices=[('', 'No'), (True, 'Yes')], coerce=bool)
submit = SubmitField("Submit Post")
@app.route("/new-post", methods=["GET", "POST"])
def new_post():
form = NewCafe(active=True)
if request.method == 'POST':
new_post = Cafe(
name=request.form.get('name'),
map_url=request.form.get('map_url'),
location=request.form.get('location'),
img_url=request.form.get('img_url'),
has_sockets=bool(request.form.get("sockets")),
has_toilet=bool(request.form.get("toilet")),
has_wifi=bool(request.form.get("wifi")),
can_take_calls=bool(request.form.get("calls")),
coffee_price=request.form.get("coffee_price"),
seats=request.form.get("seats"),
)
db.session.add(new_post)
db.session.commit()
return redirect(url_for('get_all_posts'))
return render_template("make-post.html", form=form)
HTML: This is where I'm calling the form
 <div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
{{ ckeditor.load() }}
{{ ckeditor.config(name='body') }}
{{ wtf.quick_form(form, novalidate=True, button_map={"submit": "primary"}) }}
</div>
</div>
</div>
答案1
得分: 1
我不使用这些库,所以我不确定你使用的版本,但我认为你需要:
- 调用 
form.validate_on_submit()。 - 然后从 
form.has_toilet.data中检索数据,模式为<form变量>.<字段属性>.data。 
我认为问题是你从 request.form 中获取了未经验证的原始字段数据。另外,似乎有一些字段名称与表单定义不匹配。以下是我使用的更新后的代码:
@app.route("/new-post", methods=["GET", "POST"])
def new_post():
    form = NewCafe()
    if form.validate_on_submit():
        new_post = Cafe(
            name=form.name.data,
            map_url=form.map_url.data,
            location=form.location.data,
            img_url=form.img_url.data,
            has_sockets=form.has_sockets.data,
            has_toilet=form.has_toilet.data,
            has_wifi=form.has_wifi.data,
            can_take_calls=form.can_take_calls.data,
            coffee_price=form.coffee_price.data,
            seats=form.seats.data,
        )
        db.session.add(new_post)
        db.session.commit()
        return redirect(url_for('get_all_posts'))
    return render_template("make-post.html", form=form)
我使用以下版本进行了测试:
- flask_wtf 1.0.1
 - flask 2.2.2
 - sqlalchemy 1.4.46
 - Flask-Bootstrap 3.3.7.1
 - WTForms 3.0.1
 - flask-sqlalchemy 3.0.2
 
英文:
I don't use these libs so I'm not sure which versions you are using but I think you need to:
- call 
form.validate_on_submit(). - then retrieve data from 
form.has_toilet.data, in the pattern<form variable>.<field attribute>.data 
I think the problem was you were getting raw unvalidated field data from request.form.  Also seems that some of your field names didn't match the form definition.  Here is the updated code I used:
@app.route("/new-post", methods=["GET", "POST"])
def new_post():
    form = NewCafe()
    if form.validate_on_submit():
        new_post = Cafe(
            name=form.name.data,
            map_url=form.map_url.data,
            location=form.location.data,
            img_url=form.img_url.data,
            has_sockets=form.has_sockets.data,
            has_toilet=form.has_toilet.data,
            has_wifi=form.has_wifi.data,
            can_take_calls=form.can_take_calls.data,
            coffee_price=form.coffee_price.data,
            seats=form.seats.data,
        )
        db.session.add(new_post)
        db.session.commit()
        return redirect(url_for('get_all_posts'))
    return render_template("make-post.html", form=form)
I tested this with:
- flask_wtf 1.0.1
 - flask 2.2.2
 - sqlalchemy 1.4.46
 - Flask-Bootstrap 3.3.7.1
 - WTForms 3.0.1
 - flask-sqlalchemy 3.0.2
 
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论