Flask render_template is not passing context properly?


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:

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)

        #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 %}
{% endblock %}

{% block main %}

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


{% 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.


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.

Answered By – Jürgen Gmach

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published