Display table from SQL query in HTML


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?


See code below:


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()
            cur.execute("""select * from table1 where id = 3;""")
        query = cur.fetchall()
        return render(request, 'leaderboard/leaderboard.html', {'query': query})


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

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


{% extends 'base.html' %}

    {% block head %}
    {% endblock %}

    {% block body %}
<div class="container">
                    {% for row0 in query %}
                    <td>{{ row0.0 }}</td>
                    <td>{{ row0.1 }}</td>
                    <td>{{ row0.2 }}</td>
                        {% endfor %}
    {% endblock %}
1 Like

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.