【问题标题】:Flask Build Error烧瓶构建错误
【发布时间】:2014-01-30 19:12:44
【问题描述】:

当我填写表格时,我收到此错误,虽然它已将其添加到我的数据库中,但我没有看到 flash 消息:

werkzeug.routing.BuildError
BuildError: ('/contacts', {}, None)

我的方法:

@app.route('/contacts/', methods=['GET','POST'])
def contact_list():
    cur = g.db.execute('select contact_id, surname, firstname from address order by surname')
    contacts = cur.fetchall()
    return render_template("contacts.html", contacts = contacts) #refer to template


@app.route('/addcontact/', methods=['GET','POST'])
def contact_add():
    if request.method == 'POST':
        g.db.execute('insert into address (surname, firstname, email, mobile) values (?, ?, ?, ?)',
                 [request.form['firstname'], request.form['surname'], request.form['email']
                , request.form['mobile']])
        g.db.commit()
        flash('New entry was successfully posted')
        return redirect(url_for('/contacts')) #redirect to the contacts page
    elif request.method != 'POST':
        return render_template('addcontact.html')

我的html:

<html>
  <body>
      <h1>Add new contact</h1>
  <form action='/addcontact/' method="post">
    <dl>
      <dt>First Name:
      <dd><input type="text" size=30 name="firstname">
      <dt>Surname:
      <dd><input type="text" size=30 name="surname">
      <dt>Email:
      <dd><input type="text" size=30 name="email">
      <dt>Mobile:
      <dd><input type="text" size=30 name="mobile">            
      <dd><input type="submit" value="Add New Contact">
    </dl>
  </form>
  <a href="/">Home</a>
  <a href="/contact">List of contacts</a>

【问题讨论】:

    标签: python html sqlite flask


    【解决方案1】:

    url_for() 调用失败;你需要给它路由name,而不是url。引发异常是因为没有 /contacts 路由。这应该有效:

    url_for('contact_list')
    

    因为您调用了g.db.commit(),所以在url_for() 调用引发异常时,新联系人已经提交到数据库。

    【讨论】:

      猜你喜欢
      • 2021-04-29
      • 2013-08-19
      • 2011-04-10
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 2017-01-12
      相关资源
      最近更新 更多