【问题标题】:Getting user by primary key in flask通过烧瓶中的主键获取用户
【发布时间】:2015-02-24 12:37:59
【问题描述】:

我正在使用烧瓶并有一个包含用户名(user.html)的 html 页面,该页面取自表格,现在如何通过单击每个用户(到配置文件的路径)查看更多详细信息? 我不使用登录应用程序所以我不想使用 g

app.py

# am I doing it right?
    @app.route('/profile/<int:id>')
    def profile(id=None):
     detail = Contacts.query.get(id)
      return render_template('profile.html', detail= detail , id=id)

user.html

{% extends "layout.html" %}
{% block content %}
     <h2>show user</h2>
         {% for contact in contact  %}

          # I got error when I click on each user name to see their 'profile' 
          #I guess because of id  How can Solve it?
          #error BuildError: ('profile', {}, None)
          <strong>name:</strong><a href={{url_for('profile')}}>
            {{ contact.name}}</a><br>

           {% endfor %}
       {% endblock %}

profile.html

{% extends "layout.html" %}
{% block content %}
     <h2>show user profile</h2>
     # how can I make it specific for each row of table(each user)?
         {% for detail in Contacts  %}
           <strong>name:</strong> {{ detail.name}} <br>
           <strong>email:</strong> {{ detail.email }} <br>
           <strong>age:</strong> {{ detail.age}} <br>
           <br>
           {% endfor %}

  {% endblock %}

模型.py

class Contacts(db.Model):
   __tablename__ = "Contacts"
   id = db.Column(db.Integer, primary_key = True)
   name = db.Column(db.String(50))
   email = db.Column(db.String(50))
   age = db.Column(db.Integer)
    submit = SubmitField("Submit")

【问题讨论】:

    标签: python flask jinja2 flask-sqlalchemy


    【解决方案1】:

    我注意到您的代码中有两点:

    # this
    <a href={{url_for('profile')}}>
    
    # should be
    <a href={{url_for('profile', id=contact.id)}}>
    
    # otherwise Flask can't find the route, because it needs an id
    

    还有一个:

    {% for detail in Contacts  %}
    

    您的模板中没有Contacts 变量之类的东西,因为您的视图函数不会发送它。只需摆脱循环并直接使用detail,因为它是您发送到模板的内容。

    【讨论】:

    • @Linda 是的,对此感到抱歉。我更新了我的答案以考虑到这一点。希望对您有所帮助。
    • 非常感谢您的帮助 :) @Jivan
    猜你喜欢
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    相关资源
    最近更新 更多