Home > Net >  Flask render_template is not passing context properly?
Flask render_template is not passing context properly?

Time:09-26

I am working on a small Flask app and are having truble with either render_template() is not passing a variable through or the jinja part in the rendered html is not interpreting this correctly.

So what I have on backend side is:

@login_required
def history():
    """Show a drop down of all companies where a password is stored"""

    if request.method == "GET":

        companies = db.execute("SELECT company, website, password, type FROM pswds WHERE u_id = ?", session["user_id"])


        return render_template("dropdown.html", companies=companies)

    else:
        #company = request.form.get("comp_select")
        data = db.execute("SELECT * FROM pswds WHERE u_id = ? AND company = ?",
                        session["user_id"], request.form.get("comp_select"))
        return render_template("details.html", data=data)
        #return redirect("/details", data)

And in the template:


{% block title %}
    Details
{% endblock %}

{% block main %}

  <table class="table table-striped">
       <thead>
           <tr>
               <th headers="entry">Entry</th>
               <th headers="detail">Detail</th>
           </tr>
       </thead>
       <tbody>
           <tr>
             <td headers="entry">Company:</td>
             <td headers="detail">{{ data }}</td>
           </tr>
           <tr>
             <td headers="entry">Website:</td>
             <td headers="detail"> {{ data }}</td>
           </tr>
           <tr>
             <td headers="entry">Type:</td>
             <td headers="detail"> {{ data.type }} </td>
           </tr><tr>
             <td headers="entry">Password:</td>
             <td headers="detail"> {{ data.password }} </td>
           </tr>
       </tbody>

   </table>


{% endblock %}

Now when I do render template I can accesss the "data" variable wile only using {{ data }}. It gives the response "[{'company': 'hej', 'website': 'hej', 'password': 'test', 'type': 'hej', 'u_id': 3}]"

But when I'm for example are using {{ data.password }} I do not get any response or it is not parsed correctly.

So my main goal would be to have a table where the "Deatail" column is populated with the values from {{ data."key" }}. Can anyone point me to where my logic fails here.

BTW I'm new here and this will be my first post, so if there is anything missing in my question please let me know.

CodePudding user response:

Your database query returns a list - this is also what you printed out, e.g. [{'company': 'hej', 'website': 'hej', 'password': 'test', 'type': 'hej', 'u_id': 3}], but in your template you directly try to access e.g. the password attribute of the list - which cannot work.

So, the solution is to iterate over all results (data) in your Jinja template.

  • Related