Get Data from PostgreSQL to Django and display it in html











up vote
3
down vote

favorite












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',
}
}









share|improve this question






















  • You are not using Django to retrieve data from DB. Look at you file models.py, you d'ont import anything from Django but only psycopg2 which 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, titled Select/Fetch Records with Column Names
    – Antwane
    Jun 7 at 21:43












  • @Antwane how to use the django to retrieve data from DB? I'm beginner to django
    – Subhia
    Jun 7 at 22:54















up vote
3
down vote

favorite












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',
}
}









share|improve this question






















  • You are not using Django to retrieve data from DB. Look at you file models.py, you d'ont import anything from Django but only psycopg2 which 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, titled Select/Fetch Records with Column Names
    – Antwane
    Jun 7 at 21:43












  • @Antwane how to use the django to retrieve data from DB? I'm beginner to django
    – Subhia
    Jun 7 at 22:54













up vote
3
down vote

favorite









up vote
3
down vote

favorite











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',
}
}









share|improve this question













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',
}
}






python django postgresql






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jun 7 at 21:37









Subhia

264




264












  • You are not using Django to retrieve data from DB. Look at you file models.py, you d'ont import anything from Django but only psycopg2 which 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, titled Select/Fetch Records with Column Names
    – Antwane
    Jun 7 at 21:43












  • @Antwane how to use the django to retrieve data from DB? I'm beginner to django
    – Subhia
    Jun 7 at 22:54


















  • You are not using Django to retrieve data from DB. Look at you file models.py, you d'ont import anything from Django but only psycopg2 which 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, titled Select/Fetch Records with Column Names
    – Antwane
    Jun 7 at 21:43












  • @Antwane how to use the django to retrieve data from DB? I'm beginner to django
    – Subhia
    Jun 7 at 22:54
















You are not using Django to retrieve data from DB. Look at you file models.py, you d'ont import anything from Django but only psycopg2 which 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, titled Select/Fetch Records with Column Names
– Antwane
Jun 7 at 21:43






You are not using Django to retrieve data from DB. Look at you file models.py, you d'ont import anything from Django but only psycopg2 which 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, titled Select/Fetch Records with Column Names
– Antwane
Jun 7 at 21:43














@Antwane how to use the django to retrieve data from DB? I'm beginner to django
– Subhia
Jun 7 at 22:54




@Antwane how to use the django to retrieve data from DB? I'm beginner to django
– Subhia
Jun 7 at 22:54












1 Answer
1






active

oldest

votes

















up vote
3
down vote



accepted










django use ORM(Object-related maping) for db. It's called Model in django.



It means, you should make Model class for your db table and scheme, and django automatically make sql for the model - so you don't do sql job untill you need to.



Below is example of models. (example in docs)



from django.db import models

class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)


Django create database table like...



CREATE TABLE myapp_person (
"id" serial NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL
);


It's hard to explain all in the answer, so you must look django official docs. After following tutorials (it's well written!), you can understand django - so at least, follow tutorials.



Here's some sites for help.




  • django tutorials - Highly recommend


  • django Models docs


  • django girls tutorial - pretty good tutorials, support many languages.


  • Introducing django ORM







share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50750513%2fget-data-from-postgresql-to-django-and-display-it-in-html%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    3
    down vote



    accepted










    django use ORM(Object-related maping) for db. It's called Model in django.



    It means, you should make Model class for your db table and scheme, and django automatically make sql for the model - so you don't do sql job untill you need to.



    Below is example of models. (example in docs)



    from django.db import models

    class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)


    Django create database table like...



    CREATE TABLE myapp_person (
    "id" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL
    );


    It's hard to explain all in the answer, so you must look django official docs. After following tutorials (it's well written!), you can understand django - so at least, follow tutorials.



    Here's some sites for help.




    • django tutorials - Highly recommend


    • django Models docs


    • django girls tutorial - pretty good tutorials, support many languages.


    • Introducing django ORM







    share|improve this answer

























      up vote
      3
      down vote



      accepted










      django use ORM(Object-related maping) for db. It's called Model in django.



      It means, you should make Model class for your db table and scheme, and django automatically make sql for the model - so you don't do sql job untill you need to.



      Below is example of models. (example in docs)



      from django.db import models

      class Person(models.Model):
      first_name = models.CharField(max_length=30)
      last_name = models.CharField(max_length=30)


      Django create database table like...



      CREATE TABLE myapp_person (
      "id" serial NOT NULL PRIMARY KEY,
      "first_name" varchar(30) NOT NULL,
      "last_name" varchar(30) NOT NULL
      );


      It's hard to explain all in the answer, so you must look django official docs. After following tutorials (it's well written!), you can understand django - so at least, follow tutorials.



      Here's some sites for help.




      • django tutorials - Highly recommend


      • django Models docs


      • django girls tutorial - pretty good tutorials, support many languages.


      • Introducing django ORM







      share|improve this answer























        up vote
        3
        down vote



        accepted







        up vote
        3
        down vote



        accepted






        django use ORM(Object-related maping) for db. It's called Model in django.



        It means, you should make Model class for your db table and scheme, and django automatically make sql for the model - so you don't do sql job untill you need to.



        Below is example of models. (example in docs)



        from django.db import models

        class Person(models.Model):
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)


        Django create database table like...



        CREATE TABLE myapp_person (
        "id" serial NOT NULL PRIMARY KEY,
        "first_name" varchar(30) NOT NULL,
        "last_name" varchar(30) NOT NULL
        );


        It's hard to explain all in the answer, so you must look django official docs. After following tutorials (it's well written!), you can understand django - so at least, follow tutorials.



        Here's some sites for help.




        • django tutorials - Highly recommend


        • django Models docs


        • django girls tutorial - pretty good tutorials, support many languages.


        • Introducing django ORM







        share|improve this answer












        django use ORM(Object-related maping) for db. It's called Model in django.



        It means, you should make Model class for your db table and scheme, and django automatically make sql for the model - so you don't do sql job untill you need to.



        Below is example of models. (example in docs)



        from django.db import models

        class Person(models.Model):
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)


        Django create database table like...



        CREATE TABLE myapp_person (
        "id" serial NOT NULL PRIMARY KEY,
        "first_name" varchar(30) NOT NULL,
        "last_name" varchar(30) NOT NULL
        );


        It's hard to explain all in the answer, so you must look django official docs. After following tutorials (it's well written!), you can understand django - so at least, follow tutorials.



        Here's some sites for help.




        • django tutorials - Highly recommend


        • django Models docs


        • django girls tutorial - pretty good tutorials, support many languages.


        • Introducing django ORM








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jun 8 at 2:50









        seuling

        1,385128




        1,385128






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50750513%2fget-data-from-postgresql-to-django-and-display-it-in-html%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Paul Cézanne

            UIScrollView CustomStickyHeader Resize height generates problems when scroll is too fast

            Angular material date-picker (MatDatepicker) auto completes the date on focus out