htmlsqldjangoflaskjinja2

I can't call the data properly into my html page


I am trying to pull data from the SQL Table that I have and I am able to create a for loop for the number of items I have in the table but I am unable to pull the data.

main.py

@app.route("/Playback" , methods=['GET', 'POST'])
def Playback():
    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute("SELECT * FROM `movies`")
    query = cursor.fetchall()
    return render_template('playback.html', cursor=cursor, query=query)

playback.html

<table>
    <tr>
        <td>Movie Name:</td>
        <td>View</td>
        <td>Delete</td>
    </tr>
    {% block content %}
    {% for obj in query %}
    <tr>
        <td><p>{{ cursor['movie_name'] }}</p></td>
        <td><button>View</button></td>
        <td><button>Delete</button></td>
    </tr>
    {% endfor %}
    {% endblock %}
</table>

Here is what I have tried and the results are in the picture below: results

I am trying to pull the movie name from the table movies but the movie names from the table is not appearing. Please help. Thank you in advance.


Solution

  • It looks like there is a small mistake in your template when accessing the movie name within the loop. You are using cursor['movie_name'], but it should be obj['movie_name'] because you are iterating over query and each item in the loop is assigned to the variable obj. try this instead

    <table>
        <tr>
            <td>Movie Name:</td>
            <td>View</td>
            <td>Delete</td>
        </tr>
        {% block content %}
        {% for obj in query %}
        <tr>
            <td><p>{{ obj['movie_name'] }}</p></td>
            <td><button>View</button></td>
            <td><button>Delete</button></td>
        </tr>
        {% endfor %}
        {% endblock %}
    </table>
    

    Now I guess it should display the movie names correctly