Annotation grouping in a queryset - python

order_list = Order.objects.filter(
is_deleted=0, order_status__in=[4], order_type=0)
order_list_data = order_list.annotate(
customer_gross_sum=F('invoice__original_amount') -
F('invoice__discount_amount')+F('invoice__tax_amount'),
dcount=Count('user_id'),customer_transactions=F('invoice__transaction_invoice__transaction_amount'))
print(order_list_data.values())
from the table above, the customer_transactions in the queryset is called in the column payment in the table. The second and third in the table is of the same bill with two transactions. Is it possible to bring that under one data.
TEMPLATE
<table id="table">
<thead>
<td class="no-sort">Sl No</td>
<td class="no-sort">BILL DATE</td>
<td class="no-sort">BILL NO</td>
<td>BILL VALUE (Rs)</td>
<td>PAYMENT (Rs)</td>
<td>BALANCE (Rs)</td>
</thead>
{% for data in order_list_data %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{data.invoice.bill_date}}</td>
<td>{{data.invoice.bill_no}}</td>
<td>{{data.customer_gross_sum}}</td>
<td>{{data.customer_transactions}}</td>
<td></td>
</tr>
{% endfor %}
</table>
Expecting an output like

Related

Is there a way to change cell color in table depending on condition in Flask?

I would to change the color of cell in table depending on condition. How could I do that?
This is my code:
HTML page:
<table style="margin: 3px">
<thead>
<tr style="background-color: #7cc3a97d">
<th class="text-center">Query/File name</th>
<th class="text-center">Cosine similarity</th>
</tr>
</thead>
<tbody>
{% for key, value in cosineResults.items() %}
<tr>
<td> {{ select_query|safe }} / {{ key|safe }} </td>
{% if value|float > 0.7 %}
<td class="bg-danger"> {{ value|safe }} </td>
{% elif value|float > 0.3 %}
<td class="bg-warning"> {{ value|safe }} </td>
{% else %}
<td>{{ value|safe }}</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
It always takes the first condition (> 0.3) even if the value is smaller.
Thanks in advance

CS50 Finance: /index help displaying correct info

I've seen a few CS50 Finance help questions regarding /index. I'm trying to get the route to display a user's owned stock information (share number, value, price, etc.). Right now it displays the correct share amounts but does not display the name, value, or price (all blank). The "cash" and "grandTotal" amounts display but grandTotal is not the correct amount. I think I'm just confused on how to access specific values in my returns.
Python/sqlite:
def index():
"""Show portfolio of stocks"""
# sql queries to select stock info
user_id = session["user_id"]
stocks = db.execute("SELECT stock, symbol, SUM(shares) AS totalShares FROM purchases WHERE userid == :userid GROUP BY symbol", userid=user_id)
currentCash = db.execute("SELECT cash FROM users WHERE id == :userid", userid=user_id)
# Global variables to be updated
tableInfo = []
grandTotal = currentCash[0]["cash"]
#Grabbing info from each owned stock
for stockInfo in stocks:
symbol = stocks[0]["symbol"]
shares = stocks[0]["totalShares"]
name = stocks[0]["stock"]
currentStock = lookup(symbol)
price = currentStock["price"]
value = price * shares
grandTotal += value
tableInfo.append(stockInfo)
# Display a table with portfolio info for current user
return render_template("index.html", tableInfo=tableInfo, grandTotal=usd(grandTotal), currentCash=usd(currentCash[0]["cash"]))
HTML:
{% extends "layout.html" %}
{% block title %}
Your Portfolio
{% endblock %}
{% block main %}
<table class="table">
<thead>
<tr>
<th scope="col">Stock</th>
<th scope="col">Number of shares</th>
<th scope="col">Current price</th>
<th scope="col">Total value</th>
</tr>
</thead>
<tbody>
{% for stock in tableInfo %}
<tr>
<td>{{ stock.name }}</td>
<td>{{ stock.totalShares }}</td>
<td>{{ stock.price }}</td>
<td>{{ stock.value }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<table class="table">
<thead>
<tr>
<th scope ="col">Cash remaining</th>
<th scope ="col">Grand total</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ currentCash }}</td>
<td> {{ grandTotal }}</td>
</tr>
</tbody>
</table>
{% endblock %}

Render HTML Table with Editable WTForms FieldList and Non-Editable Values Using Jinja2 Flask

I'm using Flask and Jinja2 and I need to make an attendance table that includes both editable and non-editable fields. I referred to other posts such as here and here which got me to this point. The table successfully displays the editable fields using FieldList. However, I have not been able to render the non-editable fields.
This is what the table should look like:
The only fields which should be editable are "attendance code" and "comment". Unfortunately, I have not found a way to include the other fields (class name, start time, end time, first name, last name) as simple text fields.
I have tried using the read-only attribute for WTForms. While this is functional, it displays the text in text boxes which don't look appealing.
My latest attempt shown below defines a WTForms class called updateStudentAttendanceForm that inherits the fields from another class called attendanceLogClass that includes instance variables for the desired fields. I assign the values to the form class in the routes.py file. However, when I reference these variables in the html file, they result in blank fields. I have used a print statement to verify the variable assignments are working properly. I cannot figure out why the variables do not display properly when included in the html template.
forms.py
class attendanceLogClass:
def __init__(self):
self.classAttendanceLogId = int()
self.className = str()
self.firstName = str()
self.lastName = str()
self.startTime = datetime()
self.endTime = datetime()
def __repr__(self):
return f"attendanceLogClass('{self.classAttendanceLogId}','{self.className}','{self.firstName}','{self.lastName}','{self.startTime}','{self.endTime}')"
class updateStudentAttendanceForm(FlaskForm, attendanceLogClass):
attendanceCode = RadioField(
"Attendance Code",
choices=[("P", "P"), ("T", "T"), ("E", "E"), ("U", "U"), ("Q", "?"),],
)
comment = StringField("Comment")
submit = SubmitField("Submit Attendance")
class updateClassAttendanceForm(FlaskForm):
title = StringField("title")
classMembers = FieldList(FormField(updateStudentAttendanceForm))
routes.py
#app.route("/classattendancelog")
def displayClassAttendanceLog():
classAttendanceForm = updateClassAttendanceForm()
classAttendanceForm.title.data = "My class"
for studentAttendance in ClassAttendanceLog.query.all():
studentAttendanceForm = updateStudentAttendanceForm()
studentAttendanceForm.className = studentAttendance.ClassSchedule.className
studentAttendanceForm.classAttendanceLogId = studentAttendance.id
studentAttendanceForm.className = studentAttendance.ClassSchedule.className
studentAttendanceForm.startTime = studentAttendance.ClassSchedule.startTime
studentAttendanceForm.endTime = studentAttendance.ClassSchedule.endTime
studentAttendanceForm.firstName = (
studentAttendance.ClassSchedule.Student.firstName
)
studentAttendanceForm.lastName = (
studentAttendance.ClassSchedule.Student.lastName
)
studentAttendanceForm.attendanceCode = studentAttendance.attendanceCode
studentAttendanceForm.comment = studentAttendance.comment
# The following print statement verified that all of the variables are properly defined based on the values retrieved from the database query
print(studentAttendanceForm)
classAttendanceForm.classMembers.append_entry(studentAttendanceForm)
return render_template(
"classattendancelog.html",
title="Class Attendance Log",
classAttendanceForm=classAttendanceForm,
)
classattendancelog.html:
{% extends 'layout.html'%}
{% block content %}
<h1> Class Attendance </h1>
<form method="POST" action="" enctype="multipart/form-data">
{{ classAttendanceForm.hidden_tag() }}
<table class="table table-sm table-hover">
<thead class="thead-light">
<tr>
<th scope="col">Class Name</th>
<th scope="col">Start Time</th>
<th scope="col">End Time</th>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Attendance Code</th>
<th scope="col">Comment</th>
</tr>
</thead>
<tbody>
{% for studentAttendanceForm in classAttendanceForm.classMembers %}
<tr>
<td> {{ studentAttendanceForm.className }}</td>
<td> {{ studentAttendanceForm.startTime }}</td>
<td> {{ studentAttendanceForm.endTime }}</td>
<td> {{ studentAttendanceForm.firstName }}</td>
<td> {{ studentAttendanceForm.lastName }} </td>
<td>
{% for subfield in studentAttendanceForm.attendanceCode %}
{{ subfield }}
{{ subfield.label }}
{% endfor %}
</td>
<td>
{{ studentAttendanceForm.comment(class="form-control form-control-sm") }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}
Note: I haven't yet written the code to handle the form response.
I solved the problem by using the zip function to iterate simultaneously through two lists: one list with the FormField data and a second list with the non-editable "fixed field" data.
To use "zip" in the HTML template, I followed the instructions here and added this line to my init.py
app.jinja_env.globals.update(zip=zip)
updated forms.py (eliminated attendanceLogClass with fixed field variables):
class updateStudentAttendanceForm(FlaskForm):
attendanceCode = RadioField(
"Attendance Code",
choices=[("P", "P"), ("T", "T"), ("E", "E"), ("U", "U"), ("Q", "?"),],
)
comment = StringField("Comment")
submit = SubmitField("Submit Attendance")
class updateClassAttendanceForm(FlaskForm):
title = StringField("title")
classMembers = FieldList(FormField(updateStudentAttendanceForm))
updated routes.py (added new variable for fixed fields called classAttendanceFixedFields):
#app.route("/classattendancelog")
def displayClassAttendanceLog():
classAttendanceFixedFields = ClassAttendanceLog.query.all()
classAttendanceForm = updateClassAttendanceForm()
classAttendanceForm.title.data = "My class"
for studentAttendance in ClassAttendanceLog.query.all():
studentAttendanceForm = updateStudentAttendanceForm()
studentAttendanceForm.attendanceCode = studentAttendance.attendanceCode
studentAttendanceForm.comment = studentAttendance.comment
classAttendanceForm.classMembers.append_entry(studentAttendanceForm)
return render_template(
"classattendancelog.html",
title="Class Attendance Log",
classAttendanceForm=classAttendanceForm,
classAttendanceFixedFields=classAttendanceFixedFields,
)
updated classattendancelog.html (incorporated zip function in the for loop to simultaneously iterate through the editable fields and fixed fields).
{% extends 'layout.html'%}
{% block content %}
<h1> Class Attendance </h1>
<form method="POST" action="" enctype="multipart/form-data">
{{ classAttendanceForm.hidden_tag() }}
<table class="table table-sm table-hover">
<thead class="thead-light">
<tr>
<th scope="col">Class Name</th>
<th scope="col">Start Time</th>
<th scope="col">End Time</th>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Attendance Code</th>
<th scope="col">Comment</th>
</tr>
</thead>
<tbody>
{% for studentAttendanceForm, studentFixedFields in zip(classAttendanceForm.classMembers, classAttendanceFixedFields) %}
<tr>
<td> {{ studentFixedFields.ClassSchedule.className }}</td>
<td> {{ studentFixedFields.ClassSchedule.startTime.strftime('%-I:%M') }}</td>
<td> {{ studentFixedFields.ClassSchedule.endTime.strftime('%-I:%M') }}</td>
<td> {{ studentFixedFields.ClassSchedule.Student.firstName }}</td>
<td> {{ studentFixedFields.ClassSchedule.Student.lastName }} </td>
<td>
{% for subfield in studentAttendanceForm.attendanceCode %}
{{ subfield }}
{{ subfield.label }}
{% endfor %}
</td>
<td>
{{ studentAttendanceForm.comment(class="form-control form-control-sm") }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}

Compare Substring of Dictionary Value

I want to compare a 'term' to the values of a dictionary, specifically, the substrings of the values. This is necessary because the formatting of the values varies across different modules. For instance: module1='Doe', module2='Jane Doe'. The term to compare in this case would be 'Doe'. How should I go about solving this issue? Thanks!
search.html
{% if tickets %}
Tickets found:
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Company</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
{% for ticket in tickets %}
<tr>
<td> {{ ticket.id }} </td>
<td> {{ ticket.company.name }} </td>
<td> {{ ticket.summary }} </td>
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
views.py
def search_bar(request):
term = request.GET.get('term')
if term:
results = objCW.search_companies(term) + objCW.search_contacts(term)
tickets = objCW.search_tickets_by_company(term) + objCW.search_tickets_by_contact(term)
context = {'results': results, 'tickets': tickets}
return render(request, 'website/search.html', context)
else:
context = {'': ''}
return render(request, 'website/search.html', context)

How to display contents of a dictionary into web page using Flask

I have this problem where I can't display the contents of a dictionary into a webpage.
web_indiv[url_sequence] = {'url' : converted_url , 'name' : x.name, 'count' : web_count_current }
return render_template('video.html', web_data = web_indiv)
The web_indiv is populated using a loop, and then passed to video.html as web_data.
Sample dictionary
{1: {'url': 'http://www.drpeppersnapplegroup.com/', 'name': 'Dr. Pepper-Snapple Group', 'count': 57}, 2: {'url': 'http://www.rccolainternational.com/', 'name': 'Royal Crown Cola', 'count': 41}}
Note: It is a dictionary that contains another dictionary inside it.
This is what I already have on my html file.
{% for key1,line in web_data.items() %}
{% for key2,line_item in line.items() %}
<tr>
<td class="col-md-2">{{ line_item['url'] }}</td>
<td class="col-md-2">{{ line_item['name'] }}</td>
<td class="col-md-2">{{ line_item['count'] }}</td>
</tr>
{% endfor %}
{% endfor %}
Data won't display on the webpage.
Thank you for taking time to read my query.
If it is just a dict, you could try this:
<html>
{{web_data[url_sequence]}}
<table>
<tr>
{%for value in web_data[url_sequence].values()%}
<td class="col-md-2">{{ value }}</td>
{% endfor %}
</tr>
</table>
</html>
Note that the web_data[url_sequence] is a dictionary.
This one will have the orders (url, name and then count):
<tr>
<td class="col-md-2">{{ web_data[url_sequence].url }}</td>
<td class="col-md-2">{{ web_data[url_sequence].name }}</td>
<td class="col-md-2">{{ web_data[url_sequence].count }}</td>
</tr>
Real example:
Suppose you have the dictionary web_indiv, then you want to render it to template video.html
#app.route('/', methods=['GET'])
def root():
web_indiv = {}
url_sequence = 'test'
web_indiv[url_sequence] = {'url':'testabc','name':'hello','count': 4}
return render_template('video.html', web_data = web_indiv, url_sequence = url_sequence)
Then you can use the dict in template like this:
<tr>
<td class="col-md-2">{{ web_data[url_sequence].url }}</td>
<td class="col-md-2">{{ web_data[url_sequence].name }}</td>
<td class="col-md-2">{{ web_data[url_sequence].count }}</td>
</tr>
The html will show you:
testabc hello 4
{% for key2,line_item in web_data[url_sequence].items %}
<tr>
<td class="col-md-2">{{ line_item }}</td>
</tr>
{% endfor %}

Categories