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 %}