【问题标题】:Requesting and Showing an Integer from db Flask sqlAlchemy从 db Flask sqlAlchemy 请求并显示整数
【发布时间】:2017-08-10 16:01:43
【问题描述】:

我目前在一个简单的超市列表中工作,其中您有 2 个文本输入,他们在其中询问产品和价格。 Image of the program without Price Textfield

Image of the both textfields

因此,当我要求这 2 个数据输入时,它会在我的超级路线中给我一个错误,该路线是验证数据的路线。

@app.route('/super', methods=['POST'])
def add_super():
    content = request.form['content']
    #precio = request.form['precio']
    if not request.form['content'] or not request.form['precio']:
        flash('Debes ingresar un texto')
        return redirect('/')
    super = Super(content)
    #super = Super(precio)
    db.session.add(super)
    db.session.commit()
    flash('Registro guardado con exito!')
    return redirect('/')

在这里,我添加了从数据库请求数据的价格,这样我就可以调用它并稍后显示它,但这是我得到错误的地方。

这就是我的数据库的设置方式:

class Super(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text)
    precio = db.Column(db.Integer)
    listo = db.Column(db.Boolean, default=False)

    def __init__(self, content,precio):
        self.content = content
        self.precio = precio
        self.listo = False

    def __repr__(self):
        return '<Content %s>' % self.content
    # def __repr__(self):
    #      return '<Precio %s>' % self.precio
db.create_all()

【问题讨论】:

  • 你能把错误信息贴出来吗?
  • 是的,在控制台中我收到此错误.. 127.0.0.1 - - [10/Aug/2017 12:50:41] "POST /super HTTP/1.1" 500 - 在网络中在我用数据填充文本字段后,它会转到“内部服务器错误”

标签: python sqlite flask sqlalchemy


【解决方案1】:

您的Super 在其__init__ 中有2 个参数,但您只提供1 个参数。

例如,如果我们在解释器中定义会发生什么:

>>> class c1(object):
...     def __init__(self, p1, p2):
...         self.p1 = p1
...         self.p2 = p2

然后我们尝试只使用一个参数来创建一个实例:

>>> c1('spam')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 3 arguments (2 given)

这可能是您这样做时会发生的情况:

super = Super(content)

但是,如果我们提供两个参数:

>>> c1('spam','eggs')
<__main__.c1 object at 0x7f64a2f3a350>

因此,您需要使用两个参数创建 Super 实例,就像您可能想要的那样:

super = Super(content, precio)

推测一下,你所追求的大概是这样的:

@app.route('/super', methods=['POST'])
def add_super():
    content = request.form.get('content')
    precio = request.form.get('precio')
    if precio is None or content is None:
        flash('Debes ingresar un texto')
        return redirect('/')
    super = Super(content, precio)
    db.session.add(super)
    db.session.commit()
    flash('Registro guardado con exito!')
    return redirect('/')

【讨论】:

  • @CarlosNavarro 很高兴它有帮助,那么请您标记为已回答吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-18
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多