Html table rendering - django

My Django view is returning a list of dictionaries. This goes to html table through template rendering. Below is my template code,
My list of dictionary looks like below,
Results :
[{ 'name':'x','age': 20}, {'name': 'y','age': 25 }]
<table class="table table-striped" border="1" class="dataframe">
<thead>
<tr style="text-align: center;">
{% for k, v in results.0.items %}
<th>{{ k }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for x in results %}
<tr style="text-align: center;">
{% for y in x %}
<td> {{ x.y }} </td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
Expected output:
name age
x 20
y 25
But the output is blank.
Please let me know if there is anything wrong with my HTML table template.

You can use items properly in your inner loop just like the outer loop
<div>
<table class="table table-striped" border="1" class="dataframe">
<thead>
<tr style="text-align: center;">
{% for k, v in results.0.items %}
<th>{{ k }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for x in results %}
<tr style="text-align: center;">
{% for i,j in x.items %}
<td> {{ j }} </td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>

Related

How to read list in django template

Could someone shed a light to help me to solve this nested list problem in Django template.
I come across a list as such
[['Summary 1 CODE018'], [['Directory/File Name', 'Result']], [[['dir/var1/file1.txt', 'pass'], ['dir/var2/file2.txt', 'pass'], ['dir/var1/file3', 'pass']]], [[['null']]]]
How do I loop the above list so that I can get a table such as the first index is the table title, index1 is the table title and the rest (except when is it null) is the table body? Please take note that the last item could be [[['null']]] or [[['null', 'Info on directory CODEA18']]] which should be skip when null is detected.
Expected table:
Directory/File Name Result
dir/var1/file1.txt pass
dir/var2/file2.txt pass
dir/var3/file3.txt pass
My faulty code as below
<table id="myTable">
{% for list in summary %}
<tr>
<td> {{ list.0 }} </td>
<tbody>
<td> {{ list.0.0 }} </td>
<td> {{ list.0.0.0 }} </td>
</tbody>
</tr>
</table>
You list have 4 items. In that 2nd is Table heading and 3rd is table row.
We need to run 2 loops, one for thead and one for tbody
<table border>
<thead>
<tr>
{% for i in a[1][0] %}
<th>{{i}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for i in a[2][0] %}
<tr>
{% for j in i%}
<td>{{j}}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>

NoReverseMatch at /kitty_view Reverse for 'kitty' with arguments '(5,)' not found. Same url i have tried for another app and that is working [duplicate]

This question already has an answer here:
NoReverseMatch at /kitty_view Reverse for 'kitty' with arguments '(5,)' not found. 1 pattern(s) tried: ['kitty$']
(1 answer)
Closed 3 years ago.
// While rendering this kitty_view I am getting this error. Exactly the same thing I have copied from another app that is working properly. Kindly help. Exactly same thing is working for some other app.
view.py
------------------
def kitty_view(request):
kitty_list = kitty.objects.all().order_by('-cretime')
code1 = str(request.GET.get('Code'))
name1 = str(request.GET.get('nam'))
status1 = str(request.GET.get('stat'))
if (name1 is not None and name1 != ''):
kitty_list = kitty_list.filter(name=name1)
if (code1 is not None and code1 != ''):
kitty_list = kitty_list.filter(code='K00001')
if (status1 is not None and status1 != ''):
kitty_list = kitty_list.filter(status = 'A')
ctx = {'kitty': kitty_list}
return render(request, 'kitty/kitty_view.html', ctx)
Url.py
-----
urlpatterns = [
path('',views.index,name='index'),
path('kitty_view',views.kitty_view,name='kitty_view')
]
template
---------
<form class="form-signin" action="{% url 'kitty_view' %}" method="get">
{% csrf_token %}
<div class="form-row">
<div class="mb-3">
<select class="custom-select center-block" name="code" id="code">
<option value="">Choose Kitty...</option>
<!-- <option>{{ kitty1.code }}</option>
{% for i in kitty1 %}
<option value="{{ i.code }}"> {{ i.code|add:' - '|add:i.name }} </option>
{% endfor %} -->
<option>K00004</option>
<option>K00005</option>
</select>
</div>
<div class="mb-3">
<input type="text" name="nam" id="nam" class="form-control-sm center-block" placeholder="Name" autofocus>
</div>
<div class="mb-3">
<select class="custom-select center-block" name="stat" id="stat" placeholder="Status">
<option value="">Choose Status...</option>
<option>A</option>
<option>I</option>
</select>
</div>
<div class="mb-3">
<!-- Search -->
<button type="submit" class=" btn btn-info " role="button">Search</button>
</div>
</div>
</form>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Kitty Code</th>
<th scope="col">Name</th>
<th scope="col">Type</th>
<th scope="col">Start Date</th>
<th scope="col">Total Months</th>
<th scope="col">End Date</th>
<th scope="col">Total Members</th>
<th scope="col">Amount</th>
<th scope="col">Installment</th>
<th scope="col">Status</th>
<th scope="col">Details</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
{% if kitty %}
<h1>Biswajit1</h1>
{% for i in kitty %}
<h1>Biswajit</h1>
<tbody>
<tr>
<td>{{ i.id }} </td>
<td>{{ i.code }} </td>
<td>{{ i.name }} </td>
<td>{{ i.type }} </td>
<td>{{ i.startdate }} </td>
<td>{{ i.noofmonths }} </td>
<td>{{ i.enddate }} </td>
<td>{{ i.totalmembers }} </td>
<td>{{ i.totalamount }} </td>
<td>{{ i.noofinstallments }} </td>
<td>{% if i.status == 'A' %}
{{ 'Active' }}
{% else %}
{{ 'Inactive' }}
{% endif %}
</td>
</tr>
</tbody>
{% endfor %}
{% endif %}
</table>
{% endblock %}

How to persist data found in tables within a django template, in postgresql

I am scraping several sites and I show the data obtained in 6 tables within a django template.
My intention is to persist the data of the tables in postgresql, but I can not realize how to perform that task.
In principle I am trying to save the data from the second table.
For this I have created the models that I show below, as well as a view that is called: registroDivisaArgentina ().
The template is called quotes.html and within it, there are 6 tables.
I have tried to work with a class called: RegisterArgentineValues () within a forms.py file
models.py
class DivisasArgentina(models.Model):
class Meta:
ordering = ['CodigoDA']
CodigoDA = models.CharField(max_length=50, primary_key = True)
Texto_para_Reporte = models.CharField(max_length=70)
def __str__(self):
return '{}'.format(self.Texto_para_Reporte)
class ValoresDivisasArgentina(models.Model):
class Meta:
ordering = ['Dia']
DivisasArgentina = models.ForeignKey(DivisasArgentina, on_delete=models.PROTECT)
Dia = models.DateField(default=date.today)
Hora = models.DateTimeField(default=timezone.now)
Compra = models.FloatField()
Venta = models.FloatField()
Variacion_dia_anterior = models.FloatField()
ClaveComparacion = models.CharField(max_length=1)
def __str__(self):
return '{} - {} - {}'.format(self.DivisasArgentina, self.Dia, self.ClaveComparacion)
cotizaciones.html
{% extends 'base.html' %}
{% block contenido %}
<form method="POST" class="post-form">{% csrf_token %}
<div class="container">
<table class="table table-striped table-bordered" id="tab1">
<thead>
<tr>
<th>Divisas en el Mundo</th>
<th>Valor</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_mun%}
<tr>
{% for key,value in element.items %}
<td> {{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
</table>
</div>
<div class="container">
<table class="table table-striped table-bordered" id="tab2">
<thead>
<tr>
<th>Divisas en Argentina</th>
<th>Compra</th>
<th>Venta</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_arg%}
<tr>
{% for key,value in element.items %}
<td>{{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
<thead>
{{ form.as_table }}
</table>
</div>
<div class="container">
<table class="table table-striped table-bordered" id="tab3">
<thead>
<tr>
<th>Dolar Banco Nacion Argentina (Divisas)</th>
<th>Compra</th>
<th>Venta</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_exp%}
<tr>
{% for key,value in element.items %}
<td>{{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab4">
<thead>
<tr>
<th colspan="4">Dolar Futuro en Argentina</th>
</tr>
<tr>
<th>Mes 1</th>
<th>Mes 2</th>
<th>Mes 3</th>
<th>Mes 4</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_dol%}
<td>
{{ element.Valores}}
</td>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab5">
<thead>
<tr>
<th colspan="3">Indicadores Varios - Tasa Libor</th>
</tr>
<tr>
<th>Libor a 1 Mes</th>
<th>Libor a 2 Mes</th>
<th>Libor a 3 Mes</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_lib%}
<td>
{{ element.Valores }}
</td>
{% endfor %}
</tr>
</tbody>
</table>
<table class="table table-striped table-bordered" id="tab6">
<thead>
<tr>
<th>Indicadores Varios - Indice Merval y Oro</th>
<th>Valores</th>
</tr>
</thead>
<tbody>
<tr>
{%for element in cotiz_ind%}
<tr>
{% for key,value in element.items %}
<td> {{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
</tr>
</tr>
</tbody>
</table>
</div>
<div class="container" id="saveData">
<br></br>
<button type="submit" class="btn btn-primary pull-right">Guardar Datos</button>
</div>
</form>
{% endblock %}
views.py
def mostrar_cotizaciones(request):
cotiz_arg = json.loads(j_cotizaciones_argentina)
cotiz_mun = json.loads(j_cotizaciones_mundiales)
cotiz_exp = json.loads(j_cotizacion_export)
cotiz_dol = json.loads(j_dolar_futuro)
cotiz_ind = json.loads(j_indicadores)
cotiz_lib = json.loads(j_libor)
context = {'cotiz_mun': cotiz_mun,
'cotiz_arg': cotiz_arg,
'cotiz_exp': cotiz_exp,
'cotiz_dol': cotiz_dol,
'cotiz_ind': cotiz_ind,
'cotiz_lib': cotiz_lib,
}
return render(request, 'cotizaciones.html', context)
def registrarDivisaArgentina(request):
if request.method == 'POST':
formulario = RegistrarValoresDivisasArgentinas(request.POST)
if formulario.is_valid():
formulario.save()
return HttpResponseRedirect('/listadoValores')
else:
formulario = RegistrarValoresDivisasArgentinas()
formulario.setup('Registrar', css_class="btn btn-success")
return render(request, 'cotizaciones.html', {'formulario':formulario})
forms.py
from django import fla
from django.forms import ModelForm
from django import forms
from fla.models import *
class RegistrarValoresDivisasArgentinas(forms.ModelForm):
class Meta:
model = ValoresDivisasArgentina
fields= [Compra, Venta]
I have done some tests, but none has given a favorable result. Someone can tell me how to process the data (in the views and forms) that are in the tables, to be able to store them in my postgres tables ?
I do this kind of task very often, and I've found out that the combination of ScraPy with scrapy-djangoitem is a very good combo to use here.
Good luck!

How to display 2 queryset list Frond end?(Django ListView get_queryset)

I got 2 queryset list expired_item and queryset in Django ListView, but I don't know when item is expired(queryset is empty), how to display another list expired_item on frond end, no matter what I changed in abc.html, expired_item won't dispaly, I pasted my code as below:
class ABCListView(ListView):
model = ABC
ordering = ('name', 'skill_course')
context_object_name = 'abcs'
template_name = ''
def get_queryset(self, **kwargs):
# Omitted
......
......
# Omitted
expired_item = list(ABC.objects.filter(pk__in=aa).exclude(pk__in=z))
queryset = Permit.objects.filter(pk__in=z)
return queryset
And my html file of abc.html as below:
{% extends 'base.html' %}
{% block content %}
<nav aria-label="breadcrumb">
</nav>
<h2 class="mb-3">My Items list</h2>
<div class="card">
<table class="table mb-0">
<thead>
<tr>
<th>Name</th>
<th>Department</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
{% for a in abcs %}
<tr>
<td class="align-middle">{{ a.name }}</td>
<td class="align-middle">{{ a.department.get_html_badge }}</td>
<td class="align-middle badge badge-pill badge-danger">{{ a.status }}</td>
</tr>
{% empty %}
{% endfor %}
</tbody>
</table>
</div>
<h2 class="mb-3">My Expired Items list</h2>
<div class="card">
<table class="table mb-0">
<thead>
<tr>
<th>Name</th>
<th>Department</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
{% for b in expired_item %}
<tr>
<td class="align-middle">{{ b.name }}</td>
<td class="align-middle">{{ b.department.get_html_badge }}</td>
<td class="align-middle badge badge-pill badge-danger">{{ a.status }}</td>
</tr>
{% empty %}
{% endfor %}
</tbody>
</table>
</div>
<div class="card-footer">
{% endblock %}
Thanks so much for any advice!
I would suggest use a normal django view. This Generic ListView is just created for the use of one list. Just pass both querysets in your context and render your template with that.
You could also use get_context_data() but this would be more or less hacky and not the qay I would recommend.

for loop django template logic - how can I do this?

I am trying to output 2 items for each row. I have 4 items coming from db.
<table>
<tr>
{% for item in items %}
<td>
{{item.name}},{{item.size}}
</td>
{% endfor %}
</tr>
</table>
this is giving me
name1, 23m^2 | name2,20m^2 | name3,15m^2 | name4,10m^2
but i need
name1, 23m^2 | name2,20m^2
name3,15m^2 | name4,10m^2
each row being contained in separate <tr>. I am stuck how to break the loop and assign new row..
Just switch the <tr> and forloop, and also use forloop.counter and divisibleby
Something like this:
{% if items %}
<tr>
{% for item in items %}
<td>{{item.name}},{{item.size}}</td>
{% if forloop.counter|divisibleby:2 %}
</tr>
<tr>
{% endif %}
{% endfor %}
</tr>
{% endif %}
You forgot to close <td> tag.
<table>
<tr>
{% for item in items %}
<td>
{{item.name}},{{item.size}}
</td> <!-- here -->
{% endfor %}
</tr>
</table>