SelectField在数据库中没有返回布尔值

huangapple go评论46阅读模式
英文:

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(&quot;Cafe Name&quot;, validators=[DataRequired()])
map_url = StringField(&quot;Map URL&quot;, validators=[DataRequired(), URL()])
img_url = StringField(&quot;Image URL&quot;, validators=[DataRequired(), URL()])
location = StringField(&quot;Address&quot;, validators=[DataRequired()])
coffee_price = StringField(&quot;Average Price&quot;, validators=[DataRequired()])
seats = StringField(&quot;Seats?&quot;, validators=[DataRequired()])
has_toilet = SelectField(&quot;Toilet? &quot;, choices=[(&#39;&#39;, &#39;No&#39;), (True, &#39;Yes&#39;)], coerce=bool)
has_wifi = SelectField(&quot;WiFi? &quot;, choices=[(&#39;&#39;, &#39;No&#39;), (True, &#39;Yes&#39;)], coerce=bool)
has_sockets = SelectField(&quot;Sockets? &quot;, choices=[(&#39;&#39;, &#39;No&#39;), (True, &#39;Yes&#39;)], coerce=bool)
can_take_calls = SelectField(&quot;Take Calls? &quot;, choices=[(&#39;&#39;, &#39;No&#39;), (True, &#39;Yes&#39;)], coerce=bool)
submit = SubmitField(&quot;Submit Post&quot;)
@app.route(&quot;/new-post&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;])
def new_post():
form = NewCafe(active=True)
if request.method == &#39;POST&#39;:
new_post = Cafe(
name=request.form.get(&#39;name&#39;),
map_url=request.form.get(&#39;map_url&#39;),
location=request.form.get(&#39;location&#39;),
img_url=request.form.get(&#39;img_url&#39;),
has_sockets=bool(request.form.get(&quot;sockets&quot;)),
has_toilet=bool(request.form.get(&quot;toilet&quot;)),
has_wifi=bool(request.form.get(&quot;wifi&quot;)),
can_take_calls=bool(request.form.get(&quot;calls&quot;)),
coffee_price=request.form.get(&quot;coffee_price&quot;),
seats=request.form.get(&quot;seats&quot;),
)
db.session.add(new_post)
db.session.commit()
return redirect(url_for(&#39;get_all_posts&#39;))
return render_template(&quot;make-post.html&quot;, form=form)

HTML: This is where I'm calling the form

 &lt;div class=&quot;container&quot;&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;col-lg-8 col-md-10 mx-auto&quot;&gt;
{{ ckeditor.load() }}
{{ ckeditor.config(name=&#39;body&#39;) }}
{{ wtf.quick_form(form, novalidate=True, button_map={&quot;submit&quot;: &quot;primary&quot;}) }}
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

答案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 &lt;form variable&gt;.&lt;field attribute&gt;.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(&quot;/new-post&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;])
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(&#39;get_all_posts&#39;))
    return render_template(&quot;make-post.html&quot;, 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

huangapple
  • 本文由 发表于 2023年1月6日 10:23:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75026332.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定