I am trying to create a PDF from an HTML page using pdf-kit, then send that pdf as an attachment in an email.
Here is my code to create the pdf, this seems to be working:
html = render_template("office_report.html",role=role, name=name,owner=off,reps=reps,all_weekly=all_weekly,we=we,totals=totals,cog=cog,all_weekly_rpt=True,off_rpt=off_rpt,v=v,adonors=adonors,ae=ae,ov=ov,pay_total=pay_total)
options = {"enable-local-file-access": None}
try:
pdf=pdfkit.from_string(html,False,options=options)
files = pdf
except Exception as e:
print(e)
pdf='ERROR'
Then I try to send the email, but do not understand how to attach the PDF to the Email.
try:
msg = Message('Owner Report ', sender = ("Brand Drivers",BD), recipients = ['jesswholt#gmail.com',BD,comp])
msg.body = "Weekly Report" + str(we)
with app.open_resource(files) as fp:
msg.attach("Owner Report", "invoice/pdf", fp.read())
mail.mail.send(msg)
print('sent')
except Exception as e:
print(e)
Here is the HTML that is converted into the PDF
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>Childhelp</title>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<meta name="viewport" content="width=device-width" />
</head>
<body>
<div class="header">
<h4 class="title">Office Report <br>{{owner.owner_name}}<br>{{owner.office_ID}}</h4>
<p>WeekEnding: {{we.strftime('%m-%d-%Y')}}</p>
</div>
<table id="office_weekly" class="table table-hover table-striped">
<thead>
<th>Ambassador</th>
<th>Transactions</th>
<th>Total Payments</th>
<th>Items Sold</th>
<th>Hotlines</th>
<th>Bonuses</th>
<!-- <th>Total</th>-->
</thead>
<tbody>
{% for r in reps %}
<tr>
<td>
<strong>{{r.rep_name}}</strong><br>
{{r.rep_ID}}
</td>
{% for w in all_weekly if w.rep == r.rep_ID %}
<td>{{w.transactions}}</td>
<td>
Cash: ${{w.cash/100}}<br>
Check: ${{w.check/100}}<br>
Card: ${{w.card/100}}<br>
<strong>Total: ${{w.total/100}}</strong>
</td>
<td>
Sold: {{w.tot_itm}}<br>
Refunded: {{w.refunds}}<br>
Amount Refunded: {{"$%.2f" % (w.amount_refunded/100)}}<br>
Refund Dates {{w.dates_refunded}}
</td>
<td>
Active: {{w.subs}}<br>
Cancels: {{w.can}}
</td>
<td>{{"$%.2f" % (w.bonus | float)}}</td>
{% else %}
<td></td>
<td></td>
<td></td>
<td></td>
<td>Report Incomplete</td>
</tr>
{% endfor %}
{% endfor %}
<tr>
<td><hr></td>
<td><hr></td>
<td><hr></td>
<td><hr></td>
<td><hr></td>
<td><hr></td>
</tr>
</tbody>
<tbody>
<tr>
<th></th>
</tr>
<td>Office Sub Total:</td>
<td>{{totals.transactions}}
</td>
<td>
Cash: {{totals.cash}}<br>
Check: {{totals.check}}<br>
Card: {{totals.card}}<br>
Total: {{totals.sales}}<br>
Overrides: {{"$%.2f" % (ov | float)}}
</td>
<td>
Items: {{totals.t_items}}<br>
COG: {{"$%.2f" % (cog)}} per piece<br>
Total COG: {{"$%.2f" % (totals.total_cog)}}
</td>
<td>
Total Hotlines for Office:<br>
Active: {{totals.hotlines}}<br>
Canceled: {{totals.cancels}}<br>
Total Pay Hotlines: {{"$%.2f" % (totals.hotlines | float * 15)}}
</td>
<td>
Total Bonuses Paid: {{totals.bonus}}<br>
Items Refunded: {{totals.items_refunded}}<br>
Amount Refunded: {{totals.amount_refunded / 100}}
</td>
</tbody>
<tbody>
<tr>
<th> Line Items</th>
</tr>
<td></td>
<td></td>
<td><strong>Balance Carry: {{off_rpt.balance_carry}}</strong></td>
</tbody>
<tbody>
<td></td>
<td></td>
<td><strong>Deposit: {{off_rpt.deposit}}</strong></td>
</tbody>
<tbody>
<td></td>
<td></td>
<td><strong>Events: {{totals.events}}</strong></td>
</tbody>
<tbody>
<td></td>
<td></td>
<td><strong>Line Items:</strong></td>
<td>
Name: {{v.li1_n}}<br>
Amount: ${{v.li1_p}}<br>
Name: {{v.li2_n}}<br>
Amount: ${{v.li2_p}}<br>
Name: {{v.li3_n}}<br>
Amount: ${{v.li3_p}}<br>
Name: {{v.li4_n}}<br>
Amount: ${{v.li4_p}}
</td>
</tbody>
<tbody>
<td></td>
<td></td>
<td></td>
<td></td>
{% if pay_total %}
<td><strong>Owner Payout:</strong></td>
<td><strong>{{"$%.2f" % (pay_total | float)}}</strong></td>
{% else %}
<td><strong>Card Sales:</strong></td>
<td><strong>{{totals.card}}</strong></td>
{% endif %}
</tbody>
<tbody>
<td>
<h3>Hotline Signups</h3>
</td>
</tbody>
<thead>
<th>Donor Name</th>
<th>Ambassador</th>
<th>Signup Date</th>
<th>Canceled</th>
<!-- <th>Total</th>-->
</thead>
<tbody>
{% for d in adonors %}
<tr>
<td>{{d.donor_name}}</td>
{% for x in reps if x.rep_ID == d.rep_ID %}
<td>{{x.rep_name}}<br>{{x.rep_ID}}</td>
{% endfor %}
<td>{{d.monthly_start_date}}</td>
{% if d.donor_status == False %}
<td>{{d.monthly_stop_date}}</td>
{% else %}
<td style="color:green">Active</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
<div class="col-md-18">
</div>
</body>
</html>
Instead of this:
with app.open_resource(files) as fp:
msg.attach("Owner Report", "invoice/pdf", fp.read())
just do this:
msg.attach("Owner Report", "invoice/pdf", pdf)
pdf (or files) contains your file as a bytes type object. So you don't need to use open_resource and read a file, because you already have the data you need.
Related
I am attempting to iterate through a map containing arrays to an HTML email template. I can print out the data in the array but, the data does not show up in the array after finishing the loop.
html_data = """
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<br>
<br>
Date: {{date}}
<br>
<br>
Hi,
<br>
<br>
Today's Picks Are in:
<br>
<br>
<div class="card-body">
<table class="table table-sm">
<thead>
<tr>
<th align='left'>Stock</th>
<th>Pick</th>
<th>Detail</th>
<th>Change</th>
</tr>
</thead>
<tbody>
<td align='left'>{{ picks }}</td>
{% for pick in picks %}
<tr>
<td align='center'> {{pick.stock}} </td>
# <td align='center'> {{pick.prices}} </td>
# <td align='center'>{{pick.option_details}}</td>
# <td align='center'>{{pick.change}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<br>
<br>
<p>If you would like to be removed from this list, please contact customer service: <mail_to="devs#hscottindustriescom">HScottIndustries</a> </p>
"""
Picks is the mapped array
picks = {
'stocks': stocks,
'prices': stock_price,
'option_details': options_details,
'change': change
}
The data from picks is added here.
msg = MIMEText(Environment().from_string(html_data).render(picks=picks, date=date_original), "html")
The output is this:
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<br>
<br>
Date: 07-05-2022
<br>
<br>
Hi,
<br>
<br>
Today's Picks Are in:
<br>
<br>
<div class="card-body">
<table class="table table-sm">
<thead>
<tr>
<th align='left'>Stock</th>
<th>Pick</th>
<th>Detail</th>
<th>Change</th>
</tr>
</thead>
<tbody>
<td align='left'>{'stocks': ['WPP', 'NEX', 'PTEN'], 'prices': ['45.21', '8.37', '13.39'], 'option_details': ['na', 'NEX Jul 15 2022 $7.50 Put', 'PTEN Jul 15 2022 $13.00 Put'], 'change': ['-10.19%', '-11.52%', '-11.53%']}</td>
<tr>
<td align='center'> </td>
# <td align='center'> </td>
# <td align='center'></td>
# <td align='center'></td>
</tr>
<tr>
<td align='center'> </td>
# <td align='center'> </td>
# <td align='center'></td>
# <td align='center'></td>
</tr>
<tr>
<td align='center'> </td>
# <td align='center'> </td>
# <td align='center'></td>
# <td align='center'></td>
</tr>
<tr>
<td align='center'> </td>
# <td align='center'> </td>
# <td align='center'></td>
# <td align='center'></td>
</tr>
</tbody>
</table>
</div>
<br>
<br>
<p>If you would like to be removed from this list, please contact customer service: HScottIndustries </p>
<footer class="main-footer">
<strong>Copyright © 2022 <mail_to="devs#HScottIndustries.com">HScottIndustries LLC</a></strong>
How do I add the get the data to iterate correctly to the corresponding fields?
You are iterating over picks, which right now is a dictionary, meaning you will get dictionary keys in return. You can either format picks in a different way, or use an index. This format should work:
picks = [
{
'stocks': 'WPP',
'prices': '45.21',
'option_details': 'na',
'change': '-10.19%'
},
{
'stocks': 'NEX',
'prices': ...
},
...
]
Alternatively you can pass picks as zipped arrays in your view:
zipped_picks = zip(*picks.values())
Then access them with:
{% for pick in zipped_picks %}
<div> {{pick.0}} <div>
<div> {{pick.1}} <div>
<div> {{pick.2}} <div>
<div> {{pick.3}} <div>
{% endfor %}
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
I'm trying to do a block tr inside an HTML table using the Python Jinja library for Front-end. The table appears to me with the following appearance:
El código HTML es el siguiente:
<body>
<div id="testName">
{{ ca['name'] }}
</div>
<br>
<div id="testDates">
Start test Date: <span>{{ ca['start_ca'] | time_str }}</span>
<br>
End test Date: <span>{{ ca['end_ca'] | time_str }}</span>
</div>
{% for stage in ca['stages'] %}
<table class="blueTable">
<tbody style="page-break-inside: auto;" >
<tr id="rowOne">
<th style="font-weight:bolder;">Stage</th>
<th colspan="5">Start Date</th>
<th colspan="5">End Date</th>
</tr>
<tr id="rowTwo">
<td >{{ stage.name }}</td>
<td colspan="5">{{stage.start | time_str}}</td>
<td colspan="5">{{stage.end | time_str}}</td>
</tr>
<tr style="background-color: #1C6EA4; color: white;">
<th>Step ID</th>
<th>Step</th>
<th>Start Date</th>
<th>End Date</th>
<th>Expected</th>
<th>Found</th>
<th>Not Found</th>
<th>Expected Ok</th>
<th>Ok</th>
<th>Fails</th>
<th>Overall</th>
</tr>
{%for step in stage.steps%}
<tr id="filaBucle">
<th rowspan='{{ step[1] | size }}'>
{{step[0]}}
</th>
{%for s in step[1]%}
<th >{{s.name}}</th>
<td>{{s.start | time_str}}</td>
<td>{{s.end | time_str}}</td>
<td style="color:darkblue;">{{s.expected}}</td>
<td style="color:green;">{{s.found}}</td>
<td style="color:red;">{{s.not_found}}</td>
<td style="color:darkblue;">{{s.expected_ok}}</td>
<td style="color:green;">{{s.ok}}</td>
<td style="color:red;">{{s.fails}}</td>
{% if s.overall < 50 %}
<td style="color: red;">{{s.overall}}%</td>
{% elif 50 <= s.overall < 100 %}
<td colspan="1" style="color: brown;">{{s.overall}}%</td>
{% else %}
<td style="color: green;">{{s.overall}}%<br></td>
{% endif %}
{% endfor %}
</tr>
{% if step[1] | has_errors %}
<tr style="color: #F3E9EB;background-color: #8E8585; border-style: hidden;">
<th colspan="11"> Errors Details</th>
</tr>
{%for s in step[1]%}
{% if s.error_detail %}
<tr style="color: #D22020; background-color: #D3C9C9;">
<th colspan="2">Step ID: {{s._id}}</th>
<th colspan="9"> {{s.name}}</th>
</tr>
{% for detail in s.error_detail %}
<tr style="color: #D22020; background-color: #D3C9C9;">
<td colspan="11"> {{detail | replace("\n", "<br>")}}</td>
</tr>
{% endfor %}
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
</tbody>
</table>
{% endfor %}
I have tried to do everything possible with the CSS, but everything is out of place and I can't put those rows as subsections of the first column where it is numbered
What I want to do is that for a particular Cylinder Id , if cylinder is issued then the user name and the issue date will be displayed in cylinder List , like this
cylinderId | date | type | status |availability| issuedate | userName | returndate |
1 | 11/11| co2 | fill | available| 12/11(if exists)| xyz | 13/11(if exists)
so for that i used prefetch_related but it is not displaying anything in cylinder List:-
here is model:-
class Cylinder(models.Model):
stachoice=[
('Fill','fill'),
('Empty','empty')
]
substachoice=[
('Available','available'),
('Unavailable','unavailable'),
('Issued','issued')
]
cylinderId=models.CharField(max_length=50,primary_key=True,null=False)
gasName=models.CharField(max_length=200)
cylinderSize=models.CharField(max_length=30)
Status=models.CharField(max_length=40,choices=stachoice,default='fill')
Availability=models.CharField(max_length=40,choices=substachoice,default="Available")
EntryDate=models.DateTimeField(default=timezone.now)
def get_absolute_url(self):
return reverse('cylinderDetail',args=[(self.cylinderId)])
def __str__(self):
return str(self.cylinderId)
class Issue(models.Model):
cylinder=models.ForeignKey('Cylinder',on_delete=models.CASCADE)
userName=models.CharField(max_length=60,null=False)
issueDate=models.DateTimeField(default=timezone.now)
def save(self,*args,**kwargs):
if not self.pk:
if self.cylinder.Availability=='Available':
Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued'))
super().save(*args,**kwargs)
def __str__(self):
return str(self.userName)
here is cylinder list view:-
def cylinderListView(request):
cylinder=Cylinder.objects.all().prefetch_related('issue_set')
return render(request,'entry/cylinderList.html',locals())
here is cylinderList template:-
{% extends 'base.html'%}
{% block content %}
<div class="alldiv">
<h1 align="center">All Cylinder list</h1>
{% if cylinder %}
<div class='centerstage'>
<div class="post">
<table border="5" cellspacing="5" width="100%" >
<thead>
<tr bgcolor="#99c2ff"align="center">
<th height="50"
width="50">Cylinder Id</th>
<th height="50"
width="50">Date</th>
<th height="50"
width="50">Gas Name</th>
<th height="50"
width="50">Cylinder Size</th>
<th height="50"
width="50">Status</th>
<th height="50"
width="50">Availability</th>
<th height="50"
width="50">Issued Date</th>
<th height="50"
width="50">Customer</th>
<th height="50"
width="50">Return Date</th>
</thead>
<tbody>
{%for cy in cylinder%}
<tr bgcolor="#e6f0ff" align="center">
<td align="center" height="10"
width="50"><a href="{{cy.get_absolute_url}}">{{cy.cylinderId}}<a></td>
<td align="center" height="10"
width="50">{{cy.EntryDate}}</td>
<td align="center" height="10"
width="50">{{cy.gasName}}</td>
<td align="center" height="10"
width="50">
{{cy.cylinderSize}}</td>
<td align="center" height="10"
width="50">
{{cy.Status}}</td>
<td align="center" height="10"
width="50">{{cy.Availability}}</td>
<td align="center" height="10"
width="50">{{cy.issue.issueDate}}</td>
<td align="center" height="10"
width="50">{{cy.issue.userName}}</td>
</tr>
{% endfor %}
</tbody>
{% else %}
<div>
<h2>No record</h2>
</div>
</table>
</div>
</div>
</div>
{% endif %}
{% endblock %
}
I m unable to figure out that what i m missing , Is I m using prefetch_related?
You need to cycle through the issue_set like so:
{% for issue in cy.issue_set.all() %}
<td align="center" height="10" width="50">{{ issue.issueDate }}</td>
<td align="center" height="10" width="50">{{ issue.userName }}</td>
{% endfor %}
I have an HTML page with a form compiled yet with default values as a modify form, in python program i want to get the modified information, if there are. i have a ID to use for update the data in my DB with pymssql. When i get data from the form in HTML page, the ID it's get, but the CF block the program and give me the error: POST/[name_page] HTTP/1.1" 400
PYTHON
#app.route('/salva_modifiche_paziente',methods=['POST'])
def dati_paziente_modificato():
id = dett_id_paz()
cf = request.form.get['cf']
nome = request.form['nome']
cognome = request.form['cognome']
data_nascita = request.form['data_nascita']
residenza = request.form['residenza']
grado_dolore = request.form['grado_dolore']
sintomi = request.form['sintomi']
data_ricovero = request.form['data_ricovero']
data_dimissione = request.form['data_dimissione']
reparto = request.form['reparto']
n_stanza = request.form['n_stanza']
n_letto = request.form['n_letto']
modifica_paziente(id, cf, nome, cognome, data_nascita, residenza, grado_dolore, sintomi, data_ricovero,
data_dimissione, reparto, n_stanza, n_letto)
dett = dettagli_paziente_ricoverato()
return render_template('dettagli_paziente_ricoverato.html', det_paz=dett)
def modifica_paziente(id,cf,nome,cognome,data_nascita,residenza,grado_dolore,sintomi,data_ricovero,data_dimissione,reparto,n_stanza,n_letto):
connection1 = pymssql.connect(database="UNICLINIC")
connection2 = pymssql.connect(database="UNICLINIC")
cursor1 = connection1.cursor()
cursor2 = connection2.cursor()
cursor1.execute("UPDATE paziente SET CF = (%s), nome = (%s), cognome = (&s), \
data_di_nascita = (%s), residenza = (%s), grado_dolore = (%d), sintomi = (%s) WHERE ID_paziente = %d",(cf,nome,cognome,data_nascita,residenza,grado_dolore,sintomi, int(id) ))
cursor2.execute("UPDATE ricoverato SET data_ricovero = (6s), \
data_dimissione = (%s), COD_reparto = (%s), n_stanza = (%s), n_letto = (%s) \
WHERE ID_paziente = (%d)"
,(data_ricovero, data_dimissione, reparto, n_stanza, n_letto,int(id)))
connection1.commit()
connection2.commit()
cursor1.close()
cursor2.close()
connection1.close()
connection2.close()
def dett_id_paz():
id = request.form['id_paziente']
print(id)
return id
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Modifica paziente | UNICLINIC</title>
<link rel="stylesheet" href={{ url_for('static', filename='style.css') }} type="text/css" media="all"/>
</head>
<body>
<div>
<table class="head_banner">
<tr>
<td><img id="logo" src={{ url_for('static', filename='immagini/logo_uniclinic.png') }} alt="Logo UNICLINIC"/></td>
<td class="menu"><button class="menu_btn">HOME</button></td>
<td class="menu"><button class="menu_btn">LOGIN</button></td>
<td class="menu"><button class="menu_btn">CONTACTS</button></td>
</tr>
</table>
<table class="tab_hd">
<thead>
<th>
<td colspan="2" id="p_tit">Dati profilo di {{det_paz.nome}} {{det_paz.cognome}}<td>
</th>
</thead>
</table>
<table class="tab_profilo">
<form id="modifica" method="post" action="salva_modifiche_paziente" class="form">
<tr>
<td class="p_dn">ID paziente:</td>
<td class="p_dv">
{{det_paz.id}}
<input style="display:none" id="id_paziente" name="id_paziente" type="text" value="{{det_paz.id}}" />
</td>
</tr>
<tr>
<td class="p_dn">Codice Fiscale:</td>
<td class="p_dv">
<input type="text" id="cf" name="cf " value="{{det_paz.cf}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Nome:</td>
<td class="p_dv">
<input type="text" id="nome" name="nome" value="{{det_paz.nome}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Cognome:</td>
<td class="p_dv">
<input type="text" id="cognome" name="cognome" value="{{det_paz.cognome}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Data di nascita:</td>
<td class="p_dv">
<input type="date" id="data_nascita" name="data_nascita" value="{{det_paz.data_nascita}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Residenza:</td>
<td class="p_dv">
<input type="text" id="residenza" name="residenza" value="{{det_paz.residenza}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Grado dolore:</td>
<td class="p_dv">
<select name="grado_dolore" id="grd_d">
{% for g in range(10) %}
<option type="text" id="grado_dolore" name="grado_dolore" value="{{g+1}}">Grado {{g+1}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td class="p_dn">Sintomi:</td>
<td class="p_dv">
<input type="text" id="sintmi" name="sintomi" value="{{det_paz.sintomi}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Data ricovero:</td>
<td class="p_dv">
<input type="date" id="data_ricovero" name="data_ricovero" value="{{det_paz.data_ricovero}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Data dimissione:</td>
<td class="p_dv">
<input type="date" id="data_dimissione" name="data_dimissione" value="{{det_paz.data_dimissione}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Reparto ricovero:</td>
<td class="p_dv">
<label for="reparto"></label>
<select name="reparto" id="rep" class="p_dv">
{% for reparto in rep %}
<option type="text" id="reparto" name="reparto" value="{{reparto.COD_reparto}}">{{reparto.COD_reparto}} - {{reparto.nome_reparto}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td class="p_dn">Stanza nr.:</td>
<td class="p_dv">
<input type="text" id="n_stanza" name="n_stanza" value="{{det_paz.n_stanza}}"/>
</td>
</tr>
<tr>
<td class="p_dn">Letto nr.:</td>
<td class="p_dv">
<input type="text" id="n_letto" name="n_letto" value="{{det_paz.n_letto}}"/>
</td>
</tr>
<tr class="r_bd">
<td class="b_dn"><button type="submit" form="modifica" class="menu_btn_d">CONFERMA</button></td>
<td class="b_dn"><button type="reset" class="menu_btn_d">ANNULLA</button></td>
</tr>
</form>
</table>
</div>
</body>
</html>