I'm using the Django framework with SQLite DB. I'm using SQL queries in my views.py and connecting that data to render on the frontend in my dashboard.html template.
I'm having trouble iterating through each row in my database table 'scrapeddata'. When I view the dashboard, the data being rendered is all bunched up together in one div. I'm hoping to get each row in the database to render in one div each. I tried placing a for loop in my views.py but when I do that, I only get one row from the database rendered on dashboard.html. Any help is appreciated, thank you.
views.py:
def dashboard(request):
connection = sqlite3.connect('db.sqlite3')
cursor = connection.cursor()
col1 = '''SELECT companyname FROM scrapeddata ORDER BY companyname ASC'''
cursor.execute(col1)
companyname = cursor.fetchall()
col2 = '''SELECT name FROM scrapeddata'''
cursor.execute(col2)
name = cursor.fetchall()
col3 = '''SELECT portfolio FROM scrapeddata'''
cursor.execute(col3)
portfolio = cursor.fetchall()
people_data = []
data = {
'companyname': companyname,
'name': name,
'portfolio': portfolio
}
people_data.append(data)
connection.close()
if request.user.is_authenticated:
return render(request, 'dashboard.html', {'people_data':people_data})
else :
return redirect('/login')
dashboard.html: Here's the for loop in the template.
{% for data in people_data %}
<div>
<p>{{ data.companyname }}</p>
<p>{{ data.name }}</p>
<p>{{ data.portfolio }}</p>
</div>
{% endfor %}
CodePudding user response:
THe problem is you have only one item in people_data list:
people_data = []
data = {
'companyname': companyname,
'name': name,
'portfolio': portfolio
}
people_data.append(data)
you are just appending one dictionary, and each in data dictionary is a list of items. because cursor.fetchAll() returns a list.
Since companyName,name and portfolio are fetched from same table, their length is same. So in views.py
people_data = []
for i in range(len(companyName)):
data = {
'companyname': companyname[i],
'name': name[i],
'portfolio': portfolio[i]
}
people_data.append(data)
this should work