Reading a CSV file in Flask and iterating through Jinga2 - python

I am trying to display data on my web app from a CSV file using Flask. The below code reads my CSV file and assigns stocklist as the variable for my data. In the HTML code below it, using jinga logic, I iterate through stocklist however my CSV columns are returned as rows (see sample output and pic). How do I display the rows correctly?
My python function:
#app.route('/stocks')
def Stocks():
filename = 'stock_scraper - dev.csv'
data = pandas.read_csv(filename, header=0)
stocklist = list(data.values.flatten())
return render_template('stocks.html', stocklist=stocklist)
My web app for iterating through stocklist:
<table class="table table-striped table-sm">
<thead>
<tr>
<th>#</th>
<th>Ticker</th>
<th>Closing Price</th>
<th>Closing Date</th>
</tr>
</thead>
<tbody>
{% for eachstocks in stocklist%}
<tr>
<td>{{ eachstocks }}</td>
<td>{{ eachstocks }}</td>
<td>{{ eachstocks }}</td>
<td>{{ eachstocks }}</td>
</tr>
{% endfor %}
</tbody>
</table>
Output:

Haks, i removed the nested loop and added the list position in each value to fix it. Works now.
<tbody>
{% for value in stocklist %}
<tr>
<td>{{ value[0] }}</td>
<td>{{ value[1] }}</td>
<td>{{ value[2] }}</td>
<td>{{ value[3] }}</td>
</tr>
{% endfor %}
</tbody>
output
enter image description here

You shouldn't flatten the list.
Try this:
#app.route('/stocks')
def Stocks():
filename = 'stock_scraper - dev.csv'
data = pandas.read_csv(filename, header=0)
stocklist = list(data.values)
return render_template('stocks.html', stocklist=stocklist)
Then for the Jinja template:
<table class="table table-striped table-sm">
<thead>
<tr>
<th>#</th>
<th>Ticker</th>
<th>Closing Price</th>
<th>Closing Date</th>
</tr>
</thead>
<tbody>
{% for value in stocklist%}
<tr>
<td>{{ value[0] }}</td>
<td>{{ value[1] }}</td>
<td>{{ value[2] }}</td>
<td>{{ value[3] }}</td>
</tr>
{% endfor %}
</tbody>
</table>

Related

How to separate database on 2 different table html

i have database for example
id
account_id
date
1
127
2022-04-25
2
128
2022-04-25
3
127
2022-04-24
4
128
2022-04-24
And i need separate this on 2 different tables:
account_id
date header
127
2022-04-25
127
2022-04-24
and the same with 128
That's my code for 1 table and i don't know how to separate
#bp.route('/')
def main():
wcms = Wcm.query.order_by(Wcm.date.desc()).all()
return render_template('table.html', wcms=wcms)
HTML:
<table class="table table-hover table-dark wcm">
<thead>
<tr>
<th>Date</th>
<th>WCM account ID</th>
<th>Number of standard tags</th>
<th>Number of extended tags</th>
</tr>
</thead>
<tbody>
{% for wcm in wcms %}
<tr>
<td>{{ wcm.date }}</td>
<td>{{ wcm.account_id }}</td>
<td>{{ wcm.nbm_stardart_tags }}</td>
<td>{{ wcm.nbm_custom_tags }}</td>
</tr>
{% endfor %}
</tbody>
</table>
For the following code to work we need to sort the data by the grouping value first. Since you want to seperate account IDs, I chose ASC.
wcms = Wcm.query.order_by(Wcm.account_id.asc(), Wcm.date.desc()).all()
The lambda returns the account ID to collect all entries into one list. groupby returns a list of tuples, the list() call is needed to evaluate the lazy iterator creating the group. The outer list comprehensions creates a list of those grouped Wcm lists.
wcms_by_account = [
list(wcm_group)
for acc_id, wcm_group
in groupby(wcms, lambda x: x.account_id
]
List strucure:
[
[
Wcm(account_id=127, date=2022-04-25, ...),
Wcm(account_id=127, date=2022-04-24, ...),
],
[
Wcm(account_id=128, date=2022-04-25, ...),
Wcm(account_id=128, date=2022-04-24, ...),
],
...
]
Then change your Web Template to handle a list of lists, creating a new table for each inner list.
{% for wcms in wcms_by_account %}
<table class="table table-hover table-dark wcm">
<thead>
<tr>
<th>Date</th>
<th>WCM account ID</th>
<th>Number of standard tags</th>
<th>Number of extended tags</th>
</tr>
</thead>
<tbody>
{% for wcm in wcms %}
<tr>
<td>{{ wcm.date }}</td>
<td>{{ wcm.account_id }}</td>
<td>{{ wcm.nbm_stardart_tags }}</td>
<td>{{ wcm.nbm_custom_tags }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}

Display Query from SQLite3 Database into Bootstrap table

i want to display my query from SQLite3 into Bootstrap Table. but it seems doesnt work and wont display the table.
herewith my code
views.py
#main.route('/currentlist', methods=["GET"])
def current():
if request.method == 'GET':
Connection = sqlite3.connect('C:\\Backup_old\\Task\\e_ticket\\my_app\\db\\customer.db')
cursor = Connection.cursor()
query2 = "SELECT * from customer"
cursor.execute(query2)
test = cursor.fetchall()
return render_template('overview.html', testform = test)
HTML
<div class= "content">
<table id="dtBasicExample" class="table" width="100%">
<thead>
<tr>
<th class="th-sm">Date
</th>
<th class="th-sm">time
<th class="th-sm">customer
</th>
<th class="th-sm">pic
</th>
<th class="th-sm">category
</th>
<th class="th-sm">description
</th>
</tr>
</thead>
<tbody>
<tr>
<td>9 December 2021</td>
<td>15:30:00</td>
<td>AB Corp.</td>
<td>Bob</td>
<td>network</td>
<td>network is down</td>
</tr>
<tr>
<td>9 December 2021</td>
<td>17:30:00</td>
<td>AB Corp.</td>
<td>Alex</td>
<td>computer</td>
<td>computer is broken</td>
</tr>
<tr>
<td>10 December 2021</td>
<td>05:32:00</td>
<td>CD Corp.</td>
<td>Bob</td>
<td>Server</td>
<td>server is down</td>
</tr>
<tr>
<td>12 December 2021</td>
<td>10:30:00</td>
<td>AB Corp.</td>
<td>Bob</td>
<td>printer</td>
<td>printer is down</td>
</tr>
</tbody>
</table>
</div>
it should be like this but with the data from DB
enter image description here
i've read many similiar question like this, but most of them use SQLAlchemy.
Any help greatly appreciated!
You need to use a loop and template variables with the data.
<tbody>
{% for row in testform %}
<tr>
<td>{{ row[0] }}</td>
<td>{{ row[1] }}</td>
<td>{{ row[2] }}</td>
<td>{{ row[3] }}</td>
<td>{{ row[4] }}</td>
<td>{{ row[5] }}</td>
</tr>
{% endfor %}
</tbody>

Fetching and display the data in a Django Template Using MYSQL RAW SQL QUERY

Here is my Django Template Used to Display The data in table Format...
enter code here
<table class="content" border="2px">
<thead>
<tr>
<th>S-No</th>
<th>Name</th>
<th>Email</th>
<th>Productname</th>
<th>Quantity</th>
<th>Price</th>
<th>Ordertime</th>
<th>Orderstatus</th>
<th>Actions</th>
</tr></thead>
<tbody>
{% for row in records %}
<tr align="center">
<td>{{row.pid}}</td>
<td>{{ row.username }}</td>
<td>{{ row.email }}</td>
<td>{{ row.productname }}</td>
<td>{{ row.quantity }}</td>
<td>{{ row.price }}</td>
<td>{{ row.ordertime }}</td>
<td>{{ row.orderstatus }}</td>
<td><input type="submit" value="Accept"> <input type="button" value="Reject"></td>
</tr>
{% endfor %}
</tbody>
</table>
And This is my Views.py Page for the fetching up of the data
def viewpro(request):
con = mysql.connector.connect(user='root', password='', host='localhost', database='company1')
cur = con.cursor()
cur.execute("SELECT * FROM user_order")
records=cur.fetchall()
print(records)
con.commit()
cur.close()
con.close()
#context = {'viewpro' : user_order.objects.all()}
return render(request, "viewpro.html", {'records':records})
But Here The problem is it display the no.of table rows same like DB(It have 4 records and table shows 4 rows But no data in the fields).....Pls Help me to get rid of that....Only using raw queries....

How to display contents of a dictionary into web page using Flask

I have this problem where I can't display the contents of a dictionary into a webpage.
web_indiv[url_sequence] = {'url' : converted_url , 'name' : x.name, 'count' : web_count_current }
return render_template('video.html', web_data = web_indiv)
The web_indiv is populated using a loop, and then passed to video.html as web_data.
Sample dictionary
{1: {'url': 'http://www.drpeppersnapplegroup.com/', 'name': 'Dr. Pepper-Snapple Group', 'count': 57}, 2: {'url': 'http://www.rccolainternational.com/', 'name': 'Royal Crown Cola', 'count': 41}}
Note: It is a dictionary that contains another dictionary inside it.
This is what I already have on my html file.
{% for key1,line in web_data.items() %}
{% for key2,line_item in line.items() %}
<tr>
<td class="col-md-2">{{ line_item['url'] }}</td>
<td class="col-md-2">{{ line_item['name'] }}</td>
<td class="col-md-2">{{ line_item['count'] }}</td>
</tr>
{% endfor %}
{% endfor %}
Data won't display on the webpage.
Thank you for taking time to read my query.
If it is just a dict, you could try this:
<html>
{{web_data[url_sequence]}}
<table>
<tr>
{%for value in web_data[url_sequence].values()%}
<td class="col-md-2">{{ value }}</td>
{% endfor %}
</tr>
</table>
</html>
Note that the web_data[url_sequence] is a dictionary.
This one will have the orders (url, name and then count):
<tr>
<td class="col-md-2">{{ web_data[url_sequence].url }}</td>
<td class="col-md-2">{{ web_data[url_sequence].name }}</td>
<td class="col-md-2">{{ web_data[url_sequence].count }}</td>
</tr>
Real example:
Suppose you have the dictionary web_indiv, then you want to render it to template video.html
#app.route('/', methods=['GET'])
def root():
web_indiv = {}
url_sequence = 'test'
web_indiv[url_sequence] = {'url':'testabc','name':'hello','count': 4}
return render_template('video.html', web_data = web_indiv, url_sequence = url_sequence)
Then you can use the dict in template like this:
<tr>
<td class="col-md-2">{{ web_data[url_sequence].url }}</td>
<td class="col-md-2">{{ web_data[url_sequence].name }}</td>
<td class="col-md-2">{{ web_data[url_sequence].count }}</td>
</tr>
The html will show you:
testabc hello 4
{% for key2,line_item in web_data[url_sequence].items %}
<tr>
<td class="col-md-2">{{ line_item }}</td>
</tr>
{% endfor %}

How can I iterate multiple key from a dictionary in Django template

I have given data from views to template in django. I want to iterate these multiple keys to build a html table.
views.py
data={'pacientes':p,'inicios':i,'finales':f,'enfermedad':enf} # p, i and f are lists
return render(request,'verEnf.html',data)
I want to do something like
index.html
<table>
{% for p, i, f in pacientes, inicios, finales %} # I know that this code is not work
<tr>
<td>{{ p.nombre }}</td>
<td>{{ i }}</td>
<td>{{ f }}</td>
<tr>
{% endfor %}
</table>
p is an object from Pacientes
class Usuario(models.Model):
dni=models.CharField(max_length=9,primary_key=True)
clave=models.CharField(max_length=16)
nombre=models.CharField(max_length=30)
...
and i is a string's list as
('20-2-2014', '12-2-2014', ..., '11-5-2014')
I suppose that each index of paciente, inicio and finales are related between them.
Just as Ignacio says, you can write some code in the view, before passing it to the template in order to solve your problem.
A possible solution could be packing the values in a list of tuples like this:
[
(pacientes[0], inicios[0], finales[0]),
(pacientes[1], inicios[1], finales[1]),
...
]
You can achieve this easily by using the zip function in your view:
pacientes_data = zip(p, i, f)
data={'pacientes_data':pacientes_data,'enfermedad':enf} # p, i and f are lists
return render(request,'verEnf.html',data)
And in your template:
<table>
{% for p,i,f in pacientes_data %}
<tr>
<td>{{ p.nombre }}</td>
<td>{{ i }}</td>
<td>{{ f }}</td>
</tr>
{% endfor %}
</table>
Here is a working solution for similar task:
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Model Name</th>
<th scope="col">Device Count</th>
</tr>
</thead>
<tbody>
{% for all_model in all_models %}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<td>{{ all_model.0 }}</td>
<td>{{ all_model.1 }}</td>
</tr>
{% endfor %}
</tbody>
</table>
In view.py
all_models = []
all_models_names = [1,2,3,4]
all_models_names_values = [1,2,3,4]
all_models = zip(all_models_names,all_models_names_values)
return render(request, "sample.html",{'all_models':all_models})

Categories