Compare Substring of Dictionary Value - python

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)

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

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

Templating a directly raw query in a html table

I'm beginner in django and i'm using a read-only db, I just wanna make some selects and show it as a table in my template, but I cant return coulmn by column into my html table, help me,
I'm using a directky raw query
Model.py
from django.db import connection
# Create your models here.
def dictfetchall(cursor):
"Returns all rows from a cursor as a dict"
desc = cursor.description
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
]
def my_custom_sql(self):
with connection.cursor()as cursor:
cursor.execute("""
SELECT EQUIP_ID, LINE_CODE, PLANT_CODE
FROM tbs_rm_mnt_shift_sumr
where SUMR_YMD = '20180405' AND SIDE_CODE = 'T' AND
rownum < 20
""" )
row = dictfetchall(cursor)
return row
view.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import my_custom_sql
# Create your views here.
def show_list(request):
query= my_custom_sql(self='my_custom_sql')
return render(request,'monitoring.html', {'query': query})
monitoring.html
<table border="2" style="solid black">
<tr>
<td>Equip</td>
<td>Line</td>
<td>Plant</td>
{% for instance in query %}
{% for field, value in instance.items %}
<tr>
<td>{{ value }} </td>
</tr>
{% endfor %}
{% endfor %}
</tr>
</table>
browser output:
enter image description here
At the moment you are only outputting one td for each row.
{% for instance in query %}
{% for field, value in instance.items %}
<tr>
<td>{{ value }} </td>
</tr>
{% endfor %}
{% endfor %}
It sounds like should loop inside the tr tag:
{% for instance in query %}
<tr>
{% for field, value in instance.items %}
<td>{{ value }} </td>
{% endfor %}
</tr>
{% endfor %}
However, you can't assume the order of the keys in the dictionary, so you should either access the items by key, or rethink whether you want to use dictfetchall.
{% for instance in query %}
<tr>
<td>{{ instance.EQUIP_ID }} </td>
<td>{{ instance.LINE_ID }} </td>
<td>{{ instance.PLANT_CODE }} </td>
{% endfor %}
</tr>
{% endfor %}

How to iterate over a list in django templates? [duplicate]

This question already has answers here:
Using index from iterated list
(2 answers)
Closed 7 years ago.
I'm passing 4 lists of the same length and the length of the lists to my template. How do I iterate over the lists?
views.py
def allbooks(request):
ID = [1,2]
bookName = ["Python", "Java"]
author = ["idk", "who"]
copies = [3,7]
return render(request, 'allbooks.html',{'ID':ID,'bookName':bookName, 'author':author, 'copies':copies,'range':range(len(ID))})
allbooks.html
{% extends 'base.html' %}
{% block content %}
{% if user.is_authenticated %}
<div>
<h3>
List of books:
</h3>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Book Name</th>
<th>Author</th>
<th>Number of copies</th>
</tr>
</thead>
<tbody>
{% for x in range %}
<tr>
<td>{{id[x]}}</td>
<td>{{bookName[x]}}</td>
<td>{{author[x]}}</td>
<td>{{copies[x]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<h3>You must login to continue.</h3>
{% endif %}
{% endblock %}
I've tried replacing the variable x with {% forloop.counter0 %} but to no avail. How can I fix this?
Zip all your lists to one list of tuples:
books= zip(ID, bookName, author, copies)
return render(request, 'allbooks.html',{ "books": books} )
Than loop over it in templates like:
{% for book in books %}
<tr>
<td>{{ book.0 }}</td>
<td>{{ book.1 }}</td>
<td>{{ book.2 }} </td>
<td>{{ book.3 }}</td>
</tr>
{% endfor %}
I suggest a better structure for your book info:
books = [
{ "id":1, "name": "Python", "author":"idk", "copies": 1},
{ "id":2, "name": "Java", "author":"idk2", "copies": 3}
]
than iterate through it:
{% for book in books %}
<tr>
<td>{{ book.id }}</td>
<td>{{ book.name }}</td>
<td>{{ book.author }} </td>
<td>{{ book.copies }}</td>
</tr>
{% endfor %}

django table cell color based on expression

python 2.6, with Django 1.3.1 on Redhat 6.3
In Django how would I go about changing the background colour of a table cell depending on it's value, as in if it is over 10 it's red, between 7 and 9 it's orange, below 7 is green etc..
The data is coming from a non django database/model.
I am using a standard template to iterate over the table, but would have no problem using a custom template for this.
I see the following
Link
that deals with changing cell colour but it seems to be based on a concrete value in the cell as opposed to being within a range.
using the following test code for a view
def dashboard(request):
if request.user.is_authenticated():
user = request.user.first_name
else:
return redirect('/bcpm/login')
table_headers = ['Colmun1','Column2','Column3']
table_data = [['test1',2,3],['test2',2,4],['test3',5,5]]
page_title = 'Dashboard'
template_dict = {'header_list':table_headers, 'page_title':page_title,
'results':table_data,'username':user}
return render_to_response('dashboard.html',template_dict)enter code here
and the following generic table template:
<table border=1 width=98% style="margin-left:12px;">
<tr>
{% for item in header_list %}
<th>{{ item }}</th>
{% endfor %}
</tr>
{% for row in results %}
<tr>
{% for line in row %}
<td>{{line}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
Thanks.
Almost solved;
With the help of brianbuck below i came up with the following,
in the view:
def dashboard(request):
if request.user.is_authenticated():
user = request.user.first_name
else:
return redirect('/login'
table_headers = ['Column1','Column2','Column3']
table_data = [['name','thing',8],['name','thing',5]]
page_title = 'Dashboard'
template_dict = {'header_list':table_headers, 'page_title':page_title,
'results':table_data,'username':user}
return render_to_response('dashboard.html',template_dict)
in the template;
<table border=1 width=68% style="margin-left:12px;">
<tr>
{% for item in header_list %}
<th>{{ item }}</th>
{% endfor %}
</tr>
{% for element in results %}
<tr>
<td> {{ element.0 }} </td>
<td> {{ element.1 }} </td>
{% if element.3 > 7 %} <td class="red"> {{ element.3 }} </td>
{% else %} <td class="green"> {{ element.3 }} </td> {% endif %}
</tr>
{% endfor %}
</table>
{% endif %}
I really could not get it to do an {% if or %}
When I tried to set it up to do a
"greater than or equal to 7 or less than or equal to 8"
it would always evaluate to this expression for a number higher than 7, even though the first if statement should be true for anything higher than 9.
I am using Django 1.3 and I think there may be some limitations of the if/else and the multiple evaluations, either way I have it 80% working with two values red/green and that is good enough for the moment.
Thank you all.
Got it to work like this;
{% for element in results %}
<tr>
<td> {{ element.0 }} </td>
<td> {{ element.1 }} </td>
<td> {{ element.2 }} </td>
<td> {{ element.3 }} </td>
{% if element.4 > 8 %} <td class="red"> {{ element.4 }} </td>
{% else %}{% if element.4 > 8 or element.4 >= 5 %} <td class="orange"> {{ element.4 }} </td>
{%else %}{% if element.4 < 5 %}<td class="green"> {{ element.4 }} </td>
{% endif %}{% endif %}{% endif %}
<td> {{ element.5 }} </td>
This would not be required if you have a version of Django that supports elif or if you add some of the django snippets that are available to extend your django installation.
Hurrah.
This assumes you have three classes named:
td.red {
backgroundColor: red;
}
td.orange {
backgroundColor: orange;
}
td.green {
backgroundColor: green;
}
...
Django 1.3 doesn't have elif so you will probably have to do it a bit more clunky.
<td class="
{% if val >= 10 %}red{% endif %}
{% if val >= 7 or val <= 9 %}orange{% endif %}
{% if val < 7 %}green{% endif %}">
{{ val }}
</td>
I wanted to do this only in admin.py.
Let's say your column is called col :
You want to set the column to green if its value is bigger than 0 and to red if the opposite is true.
def TableAdmin(admin.ModelAdmin)
def col_(self, obj):
green_style = "<script>document.querySelectorAll('.green_table_elem').forEach(elem => { elem.parentElement.style.background = 'green'; })</script>"
red_style = "<script>document.querySelectorAll('.red_table_elem').forEach(elem => { elem.parentElement.style.background = 'red'; })</script>"
if obj.col > 0:
return mark_safe(f'<div class="green_table_elem">{obj.col}</div> {green_style}')
else:
return mark_safe(f'<div class="red_table_elem">{obj.col}</div> {red_style}')
list_display = ('col_',)
This colors the td (column) itself and not the added div like some answers do.

Categories