Display table from SQL query in HTML

Hi,

I am trying to display the output of a SQL query (which will be a table) from my DB to the HTML. As there are no forms being used I am unsure if I need to create the usual class in views.py or if a standard function could work?

Any ideas to why this isn’t displaying anything? Or is there a more simple approach?

Cheers,

See code below:

VIEW

class LeaderBoardView(TemplateView):
    template_name = 'leaderboard/leaderboard.html'

    def get(self, request):
        return render(request, self.template_name)

    def post(self, request):
        dbase = 'x'
        dbuser = 'y'
        conn = psycopg2.connect("host=localhost dbname=" + dbase + " user=" + dbuser)
        cur = conn.cursor()
        try:
            cur.execute("""select * from table1 where id = 3;""")
        finally:
            cur.close()
        query = cur.fetchall()
        return render(request, 'leaderboard/leaderboard.html', {'query': query})

URLS

from django.urls import path
from leaderboard.views import LeaderBoardView

urlpatterns = [
    path('leaderboard/', LeaderBoardView.as_view(template_name= 'leaderboard/leaderboard.html'), name='leaderboard'),
]

HTML

{% extends 'base.html' %}
<h1>Leaderboard</h1>

    {% block head %}
    <title>Leaderboard</title>
    {% endblock %}

    {% block body %}
<div class="container">
      <h1>Leaderboard</h1>
    <table>
                <tr>
                    <th>A</th>
                    <th>B</th>
                    <th>C</th>
                </tr>
                    {% for row0 in query %}
                <tr>
                    <td>{{ row0.0 }}</td>
                    <td>{{ row0.1 }}</td>
                    <td>{{ row0.2 }}</td>
                        {% endfor %}
                </tr>
    </table>
</div>
    {% endblock %}

Your get method isn’t retrieving any data to be rendered within the template. You’re rendering the template but haven’t supplied any data in the context to be rendered.

Also, in your post request, you’re hard-coding a database connection. This is a bad idea.

I suggest you work through the Django tutorial to learn how to integrate data with a template in a view, and how to use a database in your application.

Ken