I'm beginner in django and i'm using a read-only db, I just wanna make some selects and show it as a table in my template, but I cant return coulmn by column into my html table, help me,
I'm using a directky raw query
Model.py
from django.db import connection
# Create your models here.
def dictfetchall(cursor):
"Returns all rows from a cursor as a dict"
desc = cursor.description
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
]
def my_custom_sql(self):
with connection.cursor()as cursor:
cursor.execute("""
SELECT EQUIP_ID, LINE_CODE, PLANT_CODE
FROM tbs_rm_mnt_shift_sumr
where SUMR_YMD = '20180405' AND SIDE_CODE = 'T' AND
rownum < 20
""" )
row = dictfetchall(cursor)
return row
view.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import my_custom_sql
# Create your views here.
def show_list(request):
query= my_custom_sql(self='my_custom_sql')
return render(request,'monitoring.html', {'query': query})
monitoring.html
<table border="2" style="solid black">
<tr>
<td>Equip</td>
<td>Line</td>
<td>Plant</td>
{% for instance in query %}
{% for field, value in instance.items %}
<tr>
<td>{{ value }} </td>
</tr>
{% endfor %}
{% endfor %}
</tr>
</table>
browser output:
enter image description here
At the moment you are only outputting one td for each row.
{% for instance in query %}
{% for field, value in instance.items %}
<tr>
<td>{{ value }} </td>
</tr>
{% endfor %}
{% endfor %}
It sounds like should loop inside the tr tag:
{% for instance in query %}
<tr>
{% for field, value in instance.items %}
<td>{{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
However, you can't assume the order of the keys in the dictionary, so you should either access the items by key, or rethink whether you want to use dictfetchall.
{% for instance in query %}
<tr>
<td>{{ instance.EQUIP_ID }} </td>
<td>{{ instance.LINE_ID }} </td>
<td>{{ instance.PLANT_CODE }} </td>
{% endfor %}
</tr>
{% endfor %}
Related
I have a long process that I managed to stream into a Jinja template, but now I would like to show not only results but also that could be viewed by the user as a meaning of progress.
This is my current code: it iterates over a huge collection of items, some of which produce results and others do not. I only want to show the items that match the search.
The rendering part:
lista_pantallas = buscar_componente_stream_generate(componente, atributo, valor)
return Response(stream_template('consultas/busqueda_comp.html',
lista_pantallas=lista_pantallas,
componente=componente, atributo=atributo, valor=valor,
error_msg=err_msg))
This is the way I generate the iterator:
def buscar_componente_stream_generate(componente, atributo, valor):
with uopy.connect(...) as session:
with uopy.File(...) as fapant:
pantallas_fmpant = uopy.List()
pantallas_fmpant.select(fapant)
functor = BuscadorObjetoAtributo(componente, atributo, valor)
for idx, pantalla in enumerate(pantallas_fmpant):
try:
if print_pant:
print(f'{idx} - Pantalla: {pantalla}')
procesar_pantalla(pantalla, functor)
for item in functor.lista_objetos():
yield item
functor.borrar_objetos()
except Exception as ex:
print('{0} - {1} - {2}'.format(idx, pantalla, str(ex)))
And the Jinja2 template
{% if lista_pantallas %}
<h1>Lista de pantallas</h1>
<h2>Condición: {{ componente }}.{{ atributo }} = {{ valor }}</h2>
<h2>Ultima pantalla procesada: {{idx}} - {{pantalla}}</h2>
<table>
<thead>
<th>Pantalla</th>
<th>Atributo</th>
</thead>
<tbody>
{% for item in lista_pantallas %}
{% if loop.index0 is even() %}
{% set par_css = 'par' %}
{% else %}
{% set par_css = 'impar' %}
{% endif %}
<tr class={{ par_css }}>
<td>{{ item['fichero'] }}</td>
<td>{{ item['prop'] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
How can I refresh the template with the values of the variables idx and pantalla?
I have the this output in the browser from HTML template:
{'coin__name': 'Bitcoin', 'total': Decimal('1498824')}
{'coin__name': 'Ripple', 'total': Decimal('335227')}
How can I show in an html template separately the key and the value(without saying Decimal)?
Desired outcome:
Bitcoin, 1498824
Ripple , 335227
I provide the query and the html template below:
views.py:
test = filtered_transaction_query_by_user.values('coin__name').annotate( total = (Sum('trade_price' ) * Sum('number_of_coins'))).order_by('-total')
template.html
<table class="table table-striped">
<tr>
<th>Current dict pair</th>
<th>Just the name of the crypto</th>
<th>Just the price of the crypto</th>
</tr>
{% for item in test %}
<tr>
<td>{{ item }}</td>
<td>{{ }}</td>
<td>{{ }}</td>
</tr>
{% endfor %}
Update template with below code:
{{ test }} <!-- test is list of dictonaries -->
<br>
{% for item in test %} <!-- Loop to get each item(sub dictonary) from list-->
<br>
{% for key,value in item.items %} <!-- Getting key values pairs from each sub dictonary item -->
{% if forloop.last %} <!-- Checking if last iteration of loop just to add "::" after each value -->
{{ value }} <!-- only displying values not keys from each sub dictionary -->
{%else%}
{{value }} ,
{% endif %}
{% endfor %}
{% endfor %}
Refer to this answer for removing decimal from result.
Django: remove Decimal prefix from queryset annotated field, when requesting values
Try fetching both the key and the value from the dictionary in the loop:
{% for key, value in test.items %}
<tr>
<td>{{ key }}</td>
<td>{{ value }}</td>
</tr>
{% endfor %}
If you want to format Decimal value see docs
I am completely stuck in making index function work in cs50 finance! This function should return in a html page a table with the details of the transactions made online (details are saved in a database). But it's not working: even if there is a transaction in my database, my function doesn't find it, the table is empty.
this is my code:
def index():
"""Show portfolio of stocks"""
rows = db.execute("SELECT symbol, price, shares FROM transactions WHERE id = :user_id", user_id=session["user_id"])
transactions_info = []
total_worth = 0
for transaction_info in rows:
symbol = rows [0]["symbol"]
shares = rows [0]["shares"]
price = lookup(symbol)
worth = shares * price ["price"]
total_worth += worth
transactions_info.append(transaction_info)
return render_template("index.html", rows=rows, transactions_info=transactions_info)
And this is my HTML page:
{% extends "layout.html" %}
{% block title %}
Index
{% endblock %}
{% block main %}
<table class="table table-striped" style="width:100%">
<tr>
<th>Symbol</th>
<th>Company</th>
<th>Shares</th>
<th>Price</th>
<th>TOTAL</th>
</tr>
{% for transaction in transactions %}
<tr>
<td>{{ transaction_info.symbol }}</td>
<td>{{ transaction_info.name }}</td>
<td>{{ transaction_info.shares }}</td>
<td>{{ transaction_info.price }}</td>
<td>{{ transaction_info.worth }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
Thanks for your help!
In index() you are sending a list called transactions_info here
return render_template("index.html", rows=rows, transactions_info=transactions_info)
In the html you are looping over a list called transactions here {% for transaction in transactions %}.
I hope anyone can help me.
I query different tables (with different numbers of columns) in my MySQL db to get a preview of the first 100 rows. I want to display the values in a table.
In views.py I have the following piece of code:
cursor.execute("SELECT column_name FROM information_schema.columns WHERE
table_name = '%s';" %table)
columns = cursor.fetchall()
columns_list = [i[0] for i in columns]
cursor.execute("SELECT * FROM %s LIMIT 100;" %table)
preview = cursor.fetchall()
The code in my html template looks like this:
<table>
<tr>
{% if columns_list %}
{% for column in columns_list %}
<th>{{column}}</th>
{% endfor %}
{% endif %}
</tr>
<tr>
{% if preview %}
{% for row in preview %}
<td>{{ row.0 }}</td>
<td>{{ row.1 }}</td>
<td>{{ row.2 }}</td>
<td>{{ row.3 }}</td>
</tr>
{% endfor %}
{% endif %}
</table>
But this works only if my table has 4 columns.
Is there an easier way to split the tuples and allocate them than using lots of for loops and arrays?
Thanks for your help!
You can use a nested for loop to dynamically generate your table columns:
{% if preview %}
{% for row in preview %}
<tr>
{% for col in row %}
<td>{{ col }}</td>
{% endfor %}
</tr>
{% endfor %}
{% endif %}
Here's my problem:
I want to print a table in template which contains every object with every field
Here's my solution:
views.py
def start(request):
all_rows = Person.objects.all()
all_fields_names = Person._meta.get_fields()
content = { 'all_rows': all_rows,
'all_fields_names': all_fields_names }
return render(request, 'start.html', content)
start.html
<table class="table table-striped table-hover table-responsive">
<thead>
{% for names in all_fields_names %}<th>{{ names.name |title }}</th>{% endfor %}
</thead>
<tbody>
{% for row in all_rows %}
<tr>
<td>{{ row.name }}</td>
<td>{{ row.yabadiba }}</td>
<td>{{ row.value1 }}</td>
<td>{{ row.value2 }}</td>
</tr>
{% endfor %}
</tbody>
</table>
Everything works perfectly. The problem is, when I don't know exactly how many fields is in the class. Second of all, my solution break the DRY rule. I've tried:
getattr(row, names)
and nested loops, with no success.
Is there any simple solution?
Moreover: How to print such view for every class?
What you need is values_list query in your views, it returns tuples when iterated over. Each tuple contains the value from the respective field or expression passed into the values_list():
all_fields_names = Mileage._meta.get_fields()
value_fields = [f.name for f in all_fields_names]
all_rows = Mileage.objects.values_list(*(value_fields)) #pass fields to value_list
Then you can use nested for loop in your templates:
{% for row in all_rows %}
<tr>{% for value in row %}<td>{{ value }}</td>{% endfor %}</tr>
{% endfor %}