Home > Back-end >  Show all record in Django
Show all record in Django

Time:01-03

I have SQL Server database and I have a table, I've created a stored procedure to retrieve all records from the table and tested it. The stored procedure works properly. However, when I called it in my Django program and tried to write all records on an html page, but it shows the last record only. Here is the loginsdata.html

{% block content %}

    {% for row in rows %}
        <p> <h3>Name: {{row.name}}</h3>
            <h3>Email: {{row.email}}</h3>
            <h3>Username: {{row.userName}}</h3>
            <h3>Password: {{row.password}}</h3>
        </p>
        </br>
    {% endfor %}
{% endblock content %}

And here is the views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.db import connection
import pyodbc

def readLogin(request):
     command = 'EXEC GetLogin \'\'' 
     cursor = connection.cursor()
     cursor.execute(command)

     strHtml = ''
     while True:
          row = cursor.fetchone()
          if not row:
               break
          
          userName = row[0]
          password = row[1]
          name = row[2]
          email = row[3]

          
          rows = []
          rows.append({'userName': userName, 'password': password, 'name': name, 'email': email})
     
     cursor.close()
     return render(request, 'login/loginsdata.html', {'rows': rows}) 

CodePudding user response:

You are resetting your rows each time. You should set it before the while loop, so:

strHtml = ''
rows = []
while True:
    row = cursor.fetchone()

    if not row:
        break
      
    userName = row[0]
    password = row[1]
    name = row[2]
    email = row[3]

      
    # no rows = []
    rows.append({'userName': userName, 'password': password, 'name': name, 'email': email})

CodePudding user response:

It shows the last record only because you are declaring list in a loop try this:

# rest of your code

rows = []

while True:
      # rest of your code
      rows.append({'userName': userName, 'password': password, 'name': name, 'email': email})
  • Related