Perform sum operation in django template - python

I have a checkbox pagination where user select some of the option after user submit he get redirect to the page where he sees what all item he selected and value of the item , I want to get the sum of the value of item he selected .
<tbody>
{% for booktest in var1 %}
<tr>
<td width="100%">{{ booktest }}</td>
<td>{{ booktest.rate }}</td>
</tr>
{% endfor %}
</ul>
</tbody>
Above is the HTMl code where i get select item and i want to add all value in {{ booktest.rate }}
views.py
def ResultTest(request):
var = request.POST.get('selectedTests')
booktests = BookTest.objects.filter(test__in=var.split(','))
views.py from where i get selected checkbox data.

You can calculate the sum of the rates with the Sum aggregate function [Django-doc]:
from django.db.models import Sum
def result_test(request):
var = request.POST.get('selectedTests')
booktests = BookTest.objects.filter(test__in=var.split(','))
total_rate = booktests.aggregate(total=Sum('rate'))['total'] or 0
# …

Related

How can I add a column to a table using jinja

First of all let me tell you that I'm a beginner at this, I'm on the final project of CS50x. My project consists in a webpage that lets you add some weights into a db table, and then it displays those weights and shows you the weight gain/loss. I'm trying to show the results of a query in a table rendered in html using jinja (and python). RP is the identifier(you search for the rp). The desired output is something like this:
[Desired output]
My python code is the following:
#app.route("/weightquery", methods=["GET", "POST"])
#login_required
def weightquery():
if request.method == "POST":
weights = db.execute("SELECT rp, weight, date FROM weights WHERE rp=:rp AND sex=:sex AND user_id=:user_id ORDER BY date DESC",
rp=request.form.get("rp"), sex=request.form.get("sex"), user_id=session["user_id"])
gains = db.execute("SELECT weight FROM weights WHERE rp=:rp AND sex=:sex AND user_id=:user_id ORDER BY date DESC",
rp=request.form.get("rp"), sex=request.form.get("sex"), user_id=session["user_id"])
animal = request.form.get("rp")
for i in range(len(gains)):
for weight in gains[i]:
if i >= 0 and i < (len(gains)-1):
dif= gains[i][weight] - gains[i + 1][weight]
# Store the dif somewhere I can access.
gains[i].update({'weight': dif})
# Since the dif will always have one item less, I make sure to delete the last item.
gains[i].popitem()
return render_template("weightqueried.html", weights=weights, gains=gains, animal=animal, dif=dif)
else:
return render_template("weightquery.html")
My Html template for weightqueried.html is:
{% block main %}
<div class="container">
<h3>{{ animal }}'s information</h3>
<table class="table table-striped">
<thead>
<tr>
<th>Date</th>
<th>Weight(kg)</th>
<th>Weight dif(kg)</th>
</tr>
</thead>
<tbody>
{% for rp in weights %}
<tr>
<td>{{ rp['date'] }}</td>
<td>{{ rp['weight'] }}</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
</tfoot>
</div>
{% endblock %}
Any tips and pointers are greatly appreciated since I'm trying to learn and right now my brain is fried!
Maybe it can be simplified if gains was removed entirely. Iterate over weights, do the dif calculation, and add the result to each dictionary. Then in the template, add a <td> element for rp['dif']. If I understand the problem correctly.....

Unsure how to compute a particular value to be displayed (Python/Django)

So basically in my store, every item has a specific weight and once the customer adds whatever they want and go to checkout, they can see every single order of theirs along with the name information and weight. I want to also add the total weight of all the items together. Currently, it displays only the weight of each particular item.For exampleItem A is 2 Kg and item B is 3 kgIf customer adds 2 item A and 3 Item B It displays Item: A quantity: 2 Weight : 4kgItem: B quantity: 3 Weight: 9kg.I want to also add Total weight : 13 kg
This is my views.py
def checkout(request):
try:
current_order = Order.objects.filter(owner=1).get(status="pre-place")
except Order.DoesNotExist:
return HttpResponse("Your current order is empty<br>Go back")
else:
total_weight = 0
items = OrderDetail.objects.filter(orderID=current_order)
template_name = 'store/checkout.html'
order_details = []
for item in items:
weight = item.supplyID.weight * item.quantity
order_details.append((item, weight))
return render(request, template_name, {'order_details': order_details, 'current_order': current_order})
This is my template
<h1>Your current order</h1>
<a href="{% url 'Store:browse' %}">return to selecting
supplies</a><br><br>
<table>
<tr><th>name</th><th>item weight(kg)</th><th>qty</th><th>total
weight(kg)</th></tr>
{% for order_detail, weight in order_details %}
<tr>
<td>{{ order_detail.supplyID.name }}</td>
<td>{{ order_detail.supplyID.weight }}</td>
<td>{{ order_detail.quantity }}</td>
<td>{{ weight }}</td>
</tr>
{% endfor %}
</table>
Documentation
The context variable passed to render just has to be a dictionary , so you can do your computation of the Total Weight in views.py, place this value in the dictionary and then grab the value of the Total Weight key in your template.
For example:
def checkout(request):
try:
current_order = Order.objects.filter(owner=1).get(status="pre-place")
except Order.DoesNotExist:
return HttpResponse("Your current order is empty<br>Go back")
else:
total_weight = 0
items = OrderDetail.objects.filter(orderID=current_order)
template_name = 'store/checkout.html'
order_details = []
for item in items:
weight = item.supplyID.weight * item.quantity
order_details.append((item, weight))
total_weight +=weight
return render(request, template_name, {'order_details': order_details, 'current_order': current_order, 'Total Weight' : total_weight})
Then just use that variable in your template:
<h1>Your current order</h1>
return to selecting supplies<br><br>
<table>
<tr>
<th>name</th><th>item weight(kg)</th><th>qty</th><th>total weight(kg)</th>
</tr>
{% for order_detail, weight in order_details %}
<tr>
<td>{{ order_detail.supplyID.name }}</td>
<td>{{ order_detail.supplyID.weight }}</td>
<td>{{ order_detail.quantity }}</td>
<td>{{ weight }}</td>
</tr>
{% endfor %}
</table>
<p>The total weight of your order is:</p>
<p>{{Total Weight}}</p>
First, you should understand the difference between get() and filter(). Take a look at this.
After that we can make some changes:
def checkout(request):
try:
current_order = Order.objects.filter(owner__exact=1, status__icontains ="pre-place") # exact returns exact match, icontains(could have been iexact too if you want exact match) return not case sensitive match.
except Order.DoesNotExist:
return HttpResponse("Your current order is empty<br>Go back")
else:
items = OrderDetail.objects.filter(orderID__exact=current_order) #since it is id no need for iexact which is case insensitive.
order_details = {} # it is always suggestible to use dictionary instead of turple for easiness.
for item in items:
weight = item.supplyID.weight * item.quantity
order_details[item] = weight
total_weight = sum(order_detail.values()) #sum of total weight
context = { #clear to read and maintain
'order_details': order_details,
'current_order': current_order,
'total_weight': total_weight
}
return render(request,
'store/checkout.html', # i don't find storing url usefull
context=context)
This is your template:
<h1>Your current order</h1>
<a href="{% url 'Store:browse' %}">return to selecting
supplies</a><br><br>
<table>
<tr><th>name</th><th>item weight(kg)</th><th>qty</th><th>total
weight(kg)</th></tr>
{% for item, weight in order_details.items() %}
<tr>
<td>{{ item.supplyID.name }}</td>
<td>{{ item.supplyID.weight }}</td>
<td>{{ item.quantity }}</td>
<td>{{ weight }}</td>
</tr>
{% endfor %}
</table>

Django : render not passing context variable to template

I have this views function to fetch userid and accountnumber from AWS Dynamodb :
def dsctbl2(request):
dynamodb=boto3.client('dynamodb', region_name='us-west-2')
response = dynamodb.scan(
TableName='User-Account')
filtered = response['Items']
length = len(filtered)
for k in range(length):
accnum = filtered[k]['AccountNum']['S']
uid = filtered[k]['UserId']['S']
f = dict(AccountNum=accnum,userID=uid)
rows = list(f.items())
return render('useradd.html',{'rows': rows})
I have tried almost everything but the rows value is just not getting passed to my template. I even tried passing a simple string value and even that is not getting passed. This is my template table where I wish to display the userid and accountnum.
<div class="mytable">
<table>
<thead>
<tr>
<th>Account #</th>
<th>User Id</th>
</tr>
</thead>
<tbody>
{% for row in rows %}
<tr>
<td>{{ row.AccountNum }}</td>
<td>{{ row.UserId }}</td>
</tr>
{% endfor %}
</table>
</div>
When I hit the template , nothing shows up. No values are getting displayed except the table headings. Why is render not passing the context variable (list value)from my views to template ? I have been stuck with for about 6 hours ! Can someone resolve this issue ?
return render(request,'useradd.html',{'rows': rows})
you need to pass request as first parameter,

Django - template containing model's 'table'

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 %}

Creating an HTML table with database values in Flask

I want to display a table showing the values of three fields for each of the units in a table. Some assistance with creating the dictionary from the database and passing objects to the template would be greatly appreciated.
#app.route('/')
def index(row):
unit_count = Units.query.count()
unit = Units.query.filter_by(id=row).first()
rows = [] # Unsure how to define rows from Units db table
return render_template('table_overview.html', title='Overview', rows=rows, unit=unit)
{% for row in rows %}
<tr>
<td>{{ row.unit.idnum }}</a></td>
<td>{{ row.unit.product_code }}</td>
<td bgcolor="{{ row.unit.stat_colour }}">{{ row.unit.unit_status }}</td>
</tr>
{% endfor %}
First off your view function can't receive the row input you specify. If you're trying to show all rows in the table you can do it like this:
views.py:
#app.route('/')
def index():
rows = Units.query.all()
return render_template('table_overview.html',
title='Overview',
rows=rows)
table_overview.html (template)
{% for row in rows %}
<tr>
<td>{{ row.idnum }}</a></td>
<td>{{ row.product_code }}</td>
<td bgcolor="{{ row.stat_colour }}">{{ row.unit_status }}</td>
</tr>
{% endfor %}

Categories