I have a table in PostgreSQL database that contains two columns ID and Name. I am using django framework to get the data from the database and I want to display the data into html page. The problem is that the retrieved data is without columns name. It looks like this, and in order to use it in the html page it has to have a key for each tuple.
[(2, 'abc'), (3, 'subhi')]
I've tried to get the columns name but they are only table columns without data. Below is my Code:
models.py
import psycopg2
import pprint
def main():
conn_string = "host='localhost' dbname='music' user='postgres' password='subhi123'"
column_names = []
data_rows = []
with psycopg2.connect(conn_string) as connection:
with connection.cursor() as cursor:
cursor.execute("select id, name from music")
column_names = [desc[0] for desc in cursor.description]
for row in cursor:
data_rows.append(row)
records = cursor.fetchall()
# print out the records using pretty print
# note that the NAMES of the columns are not shown, instead just indexes.
# for most people this isn't very useful so we'll show you how to return
# columns as a dictionary (hash) in the next example.
pprint.pprint(records)
print (type(records))
print("Column names: {}\n".format(column_names))
if __name__ == "__main__":
main()
views.py
from django.http import Http404
from django.shortcuts import render
from .models import main
def index (request):
all_albums = main()
return render(request,'music/index.html',{ 'all_albums' :all_albums})
index.html
{% if all_albums %}
<ul>
{% for album in all_albums %}
<li> <a href="/music/{{ album}}/">{{ album }}</a></li>
{% endfor %}
</ul>
{% else %}
<h3> You don't have any data</h3>
{% endif %}
and the settings.py for which shows the PostgreSQL connection:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'music',
'USER': 'postgres',
'PASSWORD': 'subhi123',
'HOST': 'localhost',
'PORT': '5432',
}
}
models.py, you d'ont import anything from Django but onlypsycopg2which is the well known PostgreSQL connector for Python. You copy/pasted this code from wiki.postgresql.org/wiki/Using_psycopg2_with_PostgreSQL, so follow the advise in comment, and read the next part, titledSelect/Fetch Records with Column Names