Displaying columns form a table on a webapage in Django - django

I need to display a table from my database using only certain columns. In my view I have this:
def home_page(request):
query_results = Model.objects.filter(open=True)
return render(request, 'home.html')
and my home.html page looks like this:
<table>
<tr>
<th>Column1</th>
<th>Column2</th>
</tr>
{% for item in query_results %}
<tr>
<td>{{ item.col1 }}</td>
<td>{{ item.col2 }}</td>
<tr>
{% endfor %}
</table>
However, when I go to the page, there isn't any data in the table. Am I going about this wrong?
Thanks for your help.

You forget to include query_results to the template context. Try this:
return render(request, 'home.html', {'query_results': query_results})

Related

Django looping through items not showing

Hi I am looping through items being passed through the context but nothing is showing.
This is the data I have:
{"error":[],"result":{"USDT":"60000.00000000","CHZ":"13773.0349000000","ZRX":"0.0000000000","ZUSD":"67787.8285","DOT":"0.0000000000","COMP":"0.0000034600","ENJ":"257.6815000000","ADA":"2473.80445621","XXDG":"17006.92601155","ALGO":"32063.69514500","XXBT":"0.0000012880","SUSHI":"172.4585500000","SOL":"1133.3543869800","DASH":"0.5104491200","LINK":"144.2407000000","ATOM":"151.26763831","XXLM":"6926.27220000","XXRP":"0.00000000","XETH":"14.5877343640","TRX":"923.80015900","KNC":"0.0000000000","BAL":"0.0000000000","XLTC":"11.4923900000","KSM":"24.7142610000","SC":"0.0000000200","OCEAN":"652.6077000000","MATIC":"1838.9295772000","AAVE":"83.6218990800","ZGBP":"30622.0790","XZEC":"0.0000073100"}}
It is passed in my context like this:
def kraken(request):
""" A view to return kraken page """
context = {
'api_reply': api_reply,
}
return render(request, 'home/kraken.html', context)
And inside my template I have this:
{% for k, v in api_reply.items %}
<tr>
<td>{{ k }}</td>
<td>{{ v }}</td>
</tr>
{% endfor %}
I have no errors showing but it is not displaying, any help would be great thank you.
The items are stored in the result subelement, you thus should enumerate over api_reply.result.items, not api_reply.items:
{% for k, v in api_reply.result.items %}
<tr>
<td>{{ k }}</td>
<td>{{ v }}</td>
</tr>
{% endfor %}
Furthermore you need to convert the JSON blob into Python objects, for example with:
import json
def kraken(request):
""" A view to return kraken page """
context = {
'api_reply': json.loads(api_reply),
}
return render(request, 'home/kraken.html', context)

Django PDF Render, aggregate template tag shows up with code included

In views.py, I have the following function to render a PDF view:
def agent_render_pdf(request, *args, **kwargs):
pk = kwargs.get('pk')
agent = get_object_or_404(Agents, pk=pk)
invoices = Invoice.objects.filter(agent=agent)
invoice_total = invoices.aggregate(Sum('invoice_amount'))
template_path = 'agents/statement.html'
context = {'agent': agent,
'invoices':invoices,
'invoice_total': invoice_total,}
#Create a Django response object, and specify content_type as pdf
response = HttpResponse(content_type='application/pdf')
#if download:
#response['Content-Disposition'] = 'attachment'; filename"report.pdf"'
#if display:
response['Content-Disposition']='filename="report.pdf"'
#find the template and render it
template = get_template(template_path)
html = template.render(context)
#create a PDF
pisa_status = pisa.CreatePDF(
html, dest=response
)
if pisa_status.err:
return HttpResponse('We had some errors <pre>' +html +'</pre>')
return response
I am rendering that to 'statements.html' as follows:
<body>
{{ agent }}
<div class="table">
<table>
<th>Invoice Number</th>
<th>Invoice Date</th>
<th>Due Date</th>
<th>Invoice Amount</th>
<th>Invoice Age</th>
{% for i in invoices %}
<tr>
<td>{{ i.invoice_number }}</td>
<td>{{ i.invoice_date }}</td>
<td>{{ i.invoice_due_date|date:"m/d/Y" }}</td>
<td>{{ i.invoice_amount }}</td>
<td>{{ i.InvoiceAge }}</td>
</tr>
{% endfor %}
<tr>
<td> </td>
<td> </td>
<td>total:</td>
<td>${{ invoice_total }}</td>
<td> </td>
</tr>
</table>
</div>
My view is basically rendering as expected, accept that the invoice_total is showing up as
${'invoice_amount__sum':
Decimal('2500')}
instead of just proving the total of invoices as $2,500. I'm clearly getting the information I want, I just don't understand what I'm doing wrong that's causing the formatting issue?
The full PDF is:
Screen capture of PDF output
.aggregate() returns a dictionary, because you can get several aggregates at the same time (imagine selecting a count, a max, and a min at once, to avoid multiple queries)
So just set a key and use it:
invoice_total = invoices.aggregate(total=Sum('invoice_amount'))['total']

Django - Dynamic filters in a webpage

I am still a learner for python django. I’d like to filter dynamically data on the table below
table
The informations in my html template are :
<table>
<thead>
<tr>
<th>N°Commande</th>
<th>Magasin</th>
<th>Objet</th>
<th>Date commande</th>
<th>Montant</th>
<th>Etat</th>
</tr>
</thead>
<tbody>
{% for item in query_results %}
<tr>
<td>{{ item.numero_commande }}</td>
<td>{{ item.enseigne}}</td>
<td>{{ item.Objet}}</td>
<td>{{ item.Date_commande}}</td>
<td>{{ item.Montant}}</td>
<td>{{ item.Etat}}</td>
</tr>
</tbody>
from the class : class Commande(models.Model)
Here is an exemple of what I’d like to have (filters on table fields) :
table with dynamic filters
thank you in advance for your help
Vinloup
There's a couple of routes you could take to accomplish this, but as a beginner I think you should take a look at the django-filter library. Setup is quite simple:
pip install django-filter
Then add 'django_filters' to your INSTALLED_APPS.
INSTALLED_APPS = [
...
'django_filters',
]
Then you create a FilterSet
import django_filters
class ProductFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='iexact')
class Meta:
model = Product
fields = ['price', 'release_date']
In your view you want somethign like this (for function based views)
def product_list(request):
f = ProductFilter(request.GET, queryset=Product.objects.all())
return render(request, 'my_app/template.html', {'filter': f})
And finally in your template you want something like this
...
<form method="get">
{{ filter.form.as_p }}
<input type="submit" />
</form>
<tbody>
{% for obj in filter.qs %}
<tr>
... render your table rows here using {{ obj }}
</tr>
{% endfor %}
</tbody>
...
You could also try different setups and the documentation on the library gives you a few examples.
You can filter dynamically the context in the view function that renders this page. So when you complete the form's fields, it makes a GET request to the server, the parameters that you need to filter the data are in this request. Then, you only need to filter the query with this parameters. Here you have the Django guide for make queries. Making queries | Django
I suggest you show the function code on your view.py file so we can understand how you are filtering the data.
You can filter the table with JavaScript and a input. If you are using Bootstrap:
https://www.w3schools.com/bootstrap/bootstrap_filters.asp
Template code with Bootstrap would look like this:
<input class="form-control" id="myInput" type="text" placeholder="Search..">
<table>
<thead>
<tr>
<th>N°Commande</th>
<th>Magasin</th>
<th>Objet</th>
<th>Date commande</th>
<th>Montant</th>
<th>Etat</th>
</tr>
</thead>
<tbody id="myTable">
{% for item in query_results %}
<tr>
<td>{{ item.numero_commande }}</td>
<td>{{ item.enseigne}}</td>
<td>{{ item.Objet}}</td>
<td>{{ item.Date_commande}}</td>
<td>{{ item.Montant}}</td>
<td>{{ item.Etat}}</td>
</tr>
{% endfor %}
</tbody>
</table>
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>

Django - How to retrieve columns in template automatically from a query in views.py?

There is a module with 30 columns.
I query this table in the views.py to get the last record (last row).
To get the data in template (index.html), I have to write each column and in front of it, its value. I have to do it 30 times!
is there anything like {{form}} to get all the columns and their value automatically or at least by using {% for ... %}?
in views.py
def articlesindex(request):
data = Articles.objects.all().last()
return render(request, 'Articles\index.html', {'articles':data})
in index.html
{{ articles }} (does not work)
{{ articles.a_table }} (does not work)
{% for k,v in articles %} (does not work)
<tr>
<td>{{ k }}</td>
<td>{{ v }}</td>
</tr>
{% endfor %}
That is because last() return a single object in a queryset (see the documentation here). So, as it is a single object you will have a single row. You can render the object as follow:
<tr>
<td>{{ articles.attr_1 }}</td>
<td>{{ articles.attr_2 }}</td>
...
<td>{{ articles.attr_n }}</td>
</tr>
The attribute one by one

DJANGO render to PDF , QUERYSET

i am working on my django-admin, and i am trying to render to pdf my obj. This is my def:
def Imprimir(self, request, obj):
data = {
'id':obj.values_list('id', flat=True),
'freguesia': obj.values_list('freguesia',flat=True),
'rua': obj.values_list('rua',flat=True),
'porta': obj.values_list('porta',flat=True),
'tavaria':obj.values_list('tipo_avaria',flat=True),
}
pdf = render_to_pdf('daa/imprimir/avarias_pdf.html', data)
return HttpResponse(pdf, content_type='application/pdf')
https://i.stack.imgur.com/22V1I.png
The problem is only show my queryset and the ID, i want to show the name of the queryset not the id. anyone can help me?
My avarias_pdf.html
<table style="width:100%">
<tr>
<th>ID:</th>
<th>Freguesia:</th>
<th>Rua:</th>
<th>Porta:</th>
<th>Tipo avaria:</th>
</tr>
<tr>
<td>{{id}}</td>
<td>{{freguesia}}</td>
<td>{{rua}}</td>
<td>{{porta}} </td>
<td>{{tavaria}}</td>
</tr>
</table>
This isn't the right way to do this at all. You should remove all those values_list calls, and iterate through the queryset in the template.
def Imprimir(self, request, obj):
data = {'obj': obj}
pdf = render_to_pdf('daa/imprimir/avarias_pdf.html', data)
return HttpResponse(pdf, content_type='application/pdf')
...
{% for item in obj %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.freguesia }}</td>
<td>{{ item.rua }}</td>
<td>{{ item.porta }} </td>
<td>{{ item.tavaria }}</td>
</tr>
{% endfor %}