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 %}
Related
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)
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']
I’m new to flask, I am just trying to get a simple delete request to remove a database entry.
html table
...
{% for l in logbook %}
<tr>
<td>{{ l.TO_UTC }}</td>
<td>{{ l.LDG_UTC }}</td>
<td>{{ l.dep_airport }}</td>
<td>{{ l.arr_airport }}</td>
<td>Delete {{ l.id }}</td>
</tr>
{% endfor %}
...
the id_del refers to the delete app route:
#app.route('/logbook/delete')
def logbookdelete(id_del):
delete = Logbook.query.filter_by(id=id_del).first()
db.session.delete(delete)
db.session.commit()
return redirect(url_for('logbook'))
Current error: TypeError: logbookdelete() missing 1 required positional argument: 'id_del'
How do I get the {{ l.id }} to be used as the id_del in the app route?
Many thanks
Add <id_del> in route.
#app.route('/logbook/delete/<id_del>')
def logbookdelete(id_del):
delete = Logbook.query.filter_by(id=id_del).first()
db.session.delete(delete)
db.session.commit()
return redirect(url_for('logbook'))
def ViewCharges(request):
account = get_object_or_404(StripeAccount, team_members=request.user)
payment_requests = PaymentRequest.objects.filter(company=account).order_by('-created')
return render(request, 'dashboard/charges.html',{'payment_requests':payment_requests})
This is how my template looks after doing
{% for request in payment_requests %}
<tr>
<td>{{ request.name }}</td>
<td>{{ request.email }}</td>
<td>{{ request.amount }}</td>
<td>{{ request.paid }}</td>
<td><a href="/dashboard/charges/{{ request.pk }}" class='btn btn-dark btn-sm'>Manage</a></td>
</tr>
{% endfor %}
And in my models, I store the paid field in pence (e.g 100 = £1), this is for stripe. And I can properly format it by doing
real_amount = "{:.2f}".format(amount / 100)
this works fine until I need to do it in a for loop in html, is there a way I can do this in the html doc
<tr>
<td>Bob</td>
<td>Bob#example.com</td>
<td>£20</td>
<td>Yes</td>
<td><a href="/dashboard/charges/3523" class='btn btn-dark btn-sm'>Manage</a></td>
</tr>
The rest is fine I just need some help with that formatting, does anybody have any suggestions?
Create a property on your models to calculate real_amount. Then you can access this property in your HTML template or anywhere else just like any other field attribute of your model.
Example:
class MyModel(...):
...
#property
def real_amount(self):
return "{:.2f}".format(self.amount / 100)
Then in your templates:
{{ request.real_amount }}
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})