Linda
Linda

Reputation: 591

Getting user by primary key in flask

I'm working with flask and have a html page that contains of user name(user.html) which took from table, Now How can I see more detail by clicking on each of users(which route to profile)? I don't use login for app So I don't want to use 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 %}

model.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")

Upvotes: 0

Views: 1498

Answers (1)

Jivan
Jivan

Reputation: 23098

I noticed two things in your code:

# 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

And the other one:

{% for detail in Contacts  %}

There is no such thing as a Contacts variable in your template, because your view function does not send it. Just get rid of the loop and use detail directly, because it's what you sent to the template.

Upvotes: 1

Related Questions