How to multiply two variables together in HTML template DJANGO - html

I have this page that lists various info on a specific stock including orders that have been placed on that specific item. I would like to display how much money the user of this system would get from that specific order.
<table class='table'>
<thead>
<tr>
<th>ORDER ID</th>
<th>NAME</th>
<th>AMOUNT ORDERED</th>
<th>REVENUE</th>
<th>ORDERED ITEM</th>
<th>ADDRESS</th>
<th>CITY</th>
</tr>
</thead>
{% for x in queryset2 %}
<tr>
<td>{{x.id}}</td>
<td>{{x.name}}</td>
<td>{{x.quantity}}</td>
<td>{{x.quantity * stock.ppu}}</td>
<td>{{x.order_item}}</td>
<td>{{x.address}}</td>
<td>{{x.city}}</td>
</tr>
{% endfor %}
</table>
I have this code so far. What would be the correct syntax to multiply these two variables together : {{x.quantity * stock.ppu}}

You can not write arithmetic expressions in a Django template. You should write this in the view, for example by annotating the queryset:
from django.db.models import F
# …
queryset2 = queryset2.annotate(
total_value=F('quantity') * F('ppu')
)
then in the template you render this as:
<td>{{ x.total_value }}</td>

To do math operations in the Django template you can use this django-mathfilters
but if you try to use a built-in way to do, can follow this to add and Subtraction
Example:
{{x.quantity | add: stock.ppu}}
to do multiplication and division you can use widthratio
Example:
a*b use {% widthratio a 1 b %}
a/b use {% widthratio a b 1 %}
from this answer
or you can make your own custom tags
for add
#register.filter
def add_value(value, arg):
return value + arg
for subtract
#register.filter
def subtract(value, arg):
return value - arg
then use them in your template like this
{{x.quantity | subtract: stock.ppu}}

Related

Change the rows with the same cell value in the same color in HTML table - Django project

I created a table in my html file for my Django project, and the raw data is based on the following list (It's a very long list, so I only list a few lines):
mylist=
[{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike, 'Days':66 },
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65},
...
{'StartDate': '2021-10-5', 'ID': 34653, 'Receiver': Jack, 'Days':63}]
My Html file:
<table class="table table-striped" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>StartDate</th>
<th>ID</th>
<th>Name</th>
<th>Days</th>
</thead>
<body>
{% for element in mylist %}
<tr>
<td>{{ element.StartDate}}</td>
<td>{{ element.ID }}</td>
<td>{{ element.Receiver }}</td>
<td>{{ element.Days }}</td>
</tr>
{% endfor %}
</tbody>
</table>
I want to make all the rows with the same ID value the same color. Please advise what I should add into the <td>{{ element.ID }}</td>. Thank you!
parts of my views.py:
client = gspread.service_account_from_dict(creds)
def CreateSheet(Return_record):
sheet = client.open(Return_record).sheet1
return sheet
from sheet2api import Sheet2APIClient
sheet = client.open('Return Record 2022')
sheet_instance = sheet.get_worksheet(0)
mylist = sheet_instance.get_all_records()
mylist
def table2022(request):
return render(request,'table2022.html',{'mylist':mylist})
Everything we want to pass as context, we should keep inside view we want to use it in. It's more readable when we have more and more code.
What we are going to do, it's define a color for numbers 0-9. I'll pick some light colors for now, you can change them as you prefer.
views.py:
def table2022(request):
mylist = sheet_instance.get_all_records()
colors = {'0': 'aqua', '1': 'beige', '2': 'burlywood', '3': 'lightgrey', '4': 'silver', '5': 'skyblue', '6': 'lightblue', '7': 'lightpink', '8': 'lightgreen', '9': 'lawngreen'}
context = {'mylist': mylist, 'colors': colors}
return render(request, 'table2022.html', context)
Now, because in templates it's not that simple to use Python, we need to create custom Template Tag. Let's start with creating folder in your app, let's name it custom_tags.py. It should be created in YourProject/your_app/templatetags/ folder, so we have to also create templatetags folder in there.
custom_tags.py:
from django import template
register = template.Library()
#register.filter(name='get_color')
def get_color(colors, number):
return colors[str(number)[-1]]
your_template.html:
{% load custom_tags %}
...
{% for element in mylist %}
<tr>
<td>{{ element.StartDate }}</td>
<td style="background-color: {{ colors|get_color:element.ID }}">
{{ element.ID }}
</td>
<td>{{ element.Receiver }}</td>
<td>{{ element.Days }}</td>
</tr>
{% endfor %}
get_color tag is basically taking whole ID, then extract only last number and make it a string. After that it uses the single number as a key in colors dictionary and passes corresponding value to template, where it is going to be a valid html color.
Custom tags are used to 'implement' some Pythonic code directly into template. Don't use it too much, because most of coding should be in standard files like views.py and models.py. But sometimes there is no better way. :)
For more details about Tags, check that Django's DOCS

Pass json object to another html

I have a simple Flask application with just one table.
So python code is irrelavantly simple:
#app.route('/')
def home():
items = long_db_request()
return render_template("index.html", items=items)
#app.route('/extended')
def extended():
return render_template("animals.html")
And items is a huge JSON object.
I created a table which reflects that data:
<table>
<tr>
<th style="text-align:center">id</th>
<th style="text-align:center">creation time</th>
<th style="text-align:center">name</th>
<th style="text-align:center">animals</th>
<th style="text-align:center">number</th>
</tr>
{% for item in items %}
<tr>
<td> {{ item.id }} </td>
<td> {{ item.time }} </td>
<td>
{{ item.name }}
</td>
<td> {{item.group}} </td>
<td>{{ item.group|length }}</td>
</tr>
{% endfor %}
</table>
The table looks like:
As you can see, column animal contains a lof of object which makes it all difficult to percieve.
I want it to be like this
which is a lot easier to get. And show animals is a link to another page, where a pure json exists.
How can I achieve this?
I followed the doc of jinja2 and Flask and found method url_for() but in that case I have to pass all my json in query which is unacceptable..
How can I jump from first image to exellent nice view of the second one?
working code with the first picture is place here
Thank you very much in advance!
P.S. I only saw one question here with rellevant topic, but it does not help me
Instead of passing all the animals (e.g. cats) from one view to another, just pass the category cats to the next page.
The view function for the next page then selects all cats from the json, and passes the cats then to the detailed view.
So, on you overview page, you render links like species.html?cats (and so on), and when somebody clicks on these links the view function selects all cats, and then passes them into a render_template("species.html", species=cats) view.

TypeError: 'builtin_function_or_method' object is not iterable, How to add a dictionary with lists to html UI

I am new to FE web,
I am trying to show a datatable that constructs from a dictionary with lists inside. mt backend is python bottle.
This is my mako code:
<div class="row align-to-center">
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Source</th>
<th>Destination</th>
<th>Service</th>
<th>Action</th>
<th>Source zone</th>
<th>Destination zone</th>
<th>UID</th>
</tr>
</thead>
<tbody>
% for key, value in rules.items:
% for src in value["src_network"]:
% for dst in value["dst_network"]:
% for service in value["dst_service"]:
<tr>
<td>${src["name"]}</td>
<td>${dst["name"]}</td>
<td>${service["name"]}</td>
<td>${value["action"]}</td>
<td>${value["from_zone"]}</td>
<td>${value["to_zone"]}</td>
<td>${key}</td>
</tr>
% endfor
% endfor
% endfor
% endfor
</tbody></table>
</div>
You are trying to iterate over a function object. You must call the .items method.
Change % for key, value in rules.items: to % for key, value in rules.items():

Table appears empty without any value (Django)

My data are like this :
13.2610136284,20.8676059554,11.6376896892,0.51203356592,167,20154.4815106,
395,766,56,55047.3477967,-26818.1766435,3072.97868784,12.5402166873,-1443.
74556748,-4.0
I need to display it as a table in html
This is the function used in python to transform the data suitable for a table
import string
from datetime import datetime, date
def ratio_fil():
ratioFil = open('sergRatiosOut20170426','r')
rat = ratioFil.read().split(',')
ratioFil.close()
return rat
Rat is similar to this :
['13.2610136284', '20.8676059554', '11.6376896892', '0.51203356592',
'167', '20154.4815106', '395', '766', '56', '55047.3477967',
'-26818.1766435', '3072.97868784', '12.5402166873', '-1443.74556748',
'-4.0\r\n']
I need to put it in a table, So i create a data_table tags :
<tr><td>X</td>
<td>{{data_table.0|floatformat:1}} %</td></tr>
<tr><td>y</td>
<td>{{data_table.1|floatformat:1}} %</td></tr>
<tr><td>y1 </td>
<td>{{data_table.2|floatformat:1}} </td></tr>
<tr><td>y2</td>
<td>{{data_table.3|floatformat:1}} </td></tr>
In Html :
<div> {% with rat as data_table %}
{% include 'tags/data_table.html' %}
{% endwith %}
</div>
The table appears empty, i think it should be a method to import rat ? Please i need your help
You can use builtin for loop template tag to loop through and render the data in HTML table
<table>
<tr>
<th>Column Name</th>
</tr>
{% for data in data_table %}
<td>
<td>{{ data }} </td>
</td>
{% endfor %}
</table>
Remember to return the data from your view
def ratio_fil():
ratioFil = open('sergRatiosOut20170426','r')
rat = ratioFil.read().split(',')
ratioFil.close()
return render(request, 'template_name.html', {'data_table': rat})

Django more than 2 items in a table, template

I have been searching for a way to make a django template which can show more than 2 values per row in a table,
Let's say I have an class with 5 attributes, and I want these attribute values presented in a table on my HTML page. at first I tried with a dictionary but just 2 of the 5 attributes is not enough.
Lets say my object is like:
class ModelA(models.Model):
ID = models.IntegerField(primary_key=True, db_column='ID')
name = models.CharField(max_length=60, db_column='name')
yesorno = models.CharField(max_length=9, db_column='yes/no')
text = models.TextField(db_column='text')
description = models.TextField(db_column='description')
Now in a view I call for all these model attributes, in what datastructure should I save everything and how can I put all these 5 attributes in one row per object in a table.
(sometimes hundreds of objects may need to be shown in table (so, 100 rows))
Grab all the objects (filter accordingly).
As #init3 points out the ID is not required as Django adds that automatically, and yesorno should be a Bool.
# view.py
model_as = []
for id in ids:
try:
model_a = ModelA.objects.get(ID=id)
except ModelD.DoesNotExist:
# No model found
pass
else:
model_as.append(model_a)
return render_to_response('template.html',
{'model_as': model_as},
context_instance=RequestContext(request))
Loop over the objects in the template and print each variable in whichever column you want.
# template.html
<table>
{% for model_a in model_as %}
<tr>
<td>
{{ model_a.ID }}
{{ model_a.name }}
{{ model_a.yesorno }}
{{ model_a.text }}
{{ model_a.description }}
</td>
<tr>
{% empty %}
<tr>
<td>No ModelAs to see here</td>
<tr>
{% endfor %}
</table>