coldfusion replace function not working correctly - replace

Here is a document, stored in a variable called templlet:
{{d
{{h
Dear Customer,
We were so pleased that you have signed up for one of our programs. Below please find a listing of what you signed up for.
{{r
Sincerely Yours,
John Jones
President
XYZ Corporation
I intend to replace the {{d {{h and {{r with information selected by the user. {{d is a date, {{h is a heading and {{r is a report. The code to do this replacement is:
<cfset templlet = Replace(templlet, "{{d", "#repdatemm#")>
<cfset templlet = Replace(templlet, "{{h", "#heading#")>
<cfset templlet = Replace(templlet, "{{r", "#letrep#")>
The {{d and {{h are working fine. The {{r is being replaced with letrep, but not where it is positioned in templlet. Here is sample output:
July 06, 2018
Mr. Joseph Smith
1632 S. Bailey St.
Philadelphia, PA 19145
Dear Customer,
We were so pleased that you have signed up for one of our programs. Below please find a listing of what you signed up for.
Sincerely Yours,
John Jones
President
XYZ Corporation
Activity Code....Amount.....Note
EarlyReg.........500.00.....by check
Parking ...........30.00.......by paypal
Report Total :...530.00
(sorry for all the dots here -- I couldn't figure out how to put spaces in).
You can see that the {{r in templlet is prior to the signature, but the report is appearing after the signature line.
I've tried leaving more room in templlet between the {{r and the signature, which made no difference. I tried putting the {{r in a div, which made no difference. I'm baffled about why this is coming out in the wrong place. Can anyone tell me what is going wrong here?

The problem is that the:
<table>
Enclosing the report is not closed properly.
This works:
<cfsavecontent variable="content">
<link rel="stylesheet" href="sample.css"> <link rel="stylesheet" type = "text/css" href ="betty.css"/> <script type = "text/javascript"> fieldsplitput('moxlet', '�', 'x_1', 1) </script> <p style="margin-left:40px">{{d</p> <p style="margin-left:40px"><span style="font-size:14px"><span style="font-family:georgia,serif">{{h</span></span></p> <p style="margin-left:40px"><span style="font-size:14px"><span style="font-family:georgia,serif">Dear Customer,</span></span></p> <p style="margin-left:40px"><span style="font-size:14px"><span style="font-family:georgia,serif">We were so pleased that you have signed up for one of our programs. Apparently you live in the city of Philadelphia. Additionally we observe that you were referred to us by 191. Below please find a listing of what you signed up for.</span></span></p> <div> <p style="margin-left:40px"><span style="font-size:14px"><span style="font-family:georgia,serif"> <link rel="stylesheet" type = "text/css" href ="betty.css"/> <link rel="stylesheet" type = "text/css" href ="persrep.css"/> <style type="text/css"> #media print { table tr.page-break{page-break-before:always} } </style> <HTML> <head> <link rel="stylesheet" type = "text/css" href ="betty.css"/> </head> <body> </body> </html> <div style = "margin:auto;overflow:auto; " >{{r</span></span></p> </div> <p style="margin-left:40px"><span style="font-size:14px"><span style="font-family:georgia,serif">Sincerely Yours,</span></span></p> <p style="margin-left:40px"><span style="font-size:14px"><span style="font-family:georgia,serif">John Jones<br /> President<br /> XYZ Corporation</span></span></p>
</cfsavecontent>
<cfset date = "July 06, 2018">
<cfsavecontent variable="header">
Mr. Joseph Smith<br />
1632 S. Bailey St.<br />
Philadelphia, PA 19145
</cfsavecontent>
<cfsavecontent variable="report">
<table class = "reptable" id = 'reptable' > <tr><td> </td></tr> <td> </td> <td class = "repcolhead1">Activity Code</td> <td class = "repcolhead1">Amount Paid</td> <td class = "repcolhead1">Note</td> <td><input type = "text" id = "repfoc" class = "inpbl" value = "" style = "lineheight: 2px; width:2px" > </td> </tr> <script type = "text/Javascript"> thefocus('repfoc') function thefocus(id) { //alert("got to thefocus id is " + id); document.getElementById(id).focus(); } </script> <td style = "padding-left: 0px; padding-top: 10px " class = "repsubh"> State: PA </td> <tr> <!--up counter on this subhead where appropriate ---> <td style = "padding-left: 10px; " class = "repsubh"> Trans. Date: 11-06-2017 </td> <!--up counter on this subhead where appropriate ---> <td class = "repcolrow" style = "color: #141212; text-align: left;" > EarlyReg </td> <td class = "repcolrow" style = "color: #141212; text-align: right;" > 500.00 </td> <td class = "repcolrow" style = "color: #141212; text-align: left;" > </td> <tr> <!--up counter on this subhead where appropriate ---> <td style = "padding-left:10px; vertical-align: middle; padding-top: 5px; padding-bottom:20px; " class = "repsubf"> Subtotal: 11-06-2017 </td> <!--up counter on this subhead where appropriate ---> <td class = "repcolrow" style = "text-align: left;; vertical-align:top; padding-top: 10px color:630D85 " > <a class = "repbordtop" style = "position:relative; top:4px"> </a> </td> <script> placecount('cnt-2-1','cnt-2-2', 'brk-2-4-1', 'brk-2-4-2') </script> <td class = "repcolrow" style = "text-align: right;; vertical-align:top; padding-top: 10px color:630D85 " > <a class = "repbordtop" style = "position:relative; top:4px"> 500.00 </a> </td> <td class = "repcolrow" style = "text-align: left;; vertical-align:top; padding-top: 10px color:630D85 " > <a class = "repbordtop" style = "position:relative; top:4px"> </a> </td> <tr> <td style = "padding-left:0px; vertical-align: middle; padding-top: 5px; padding-bottom:20px; " class = "repsubf"> Subtotal: PA </td> <!--up counter on this subhead where appropriate ---> <!--up counter on this subhead where appropriate ---> <td class = "repcolrow" style = "text-align: left;; vertical-align:top; padding-top: 10px color:630D85 " > <a class = "repbordtop" style = "position:relative; top:4px"> </a> </td> <script> placecount('cnt-3-1','cnt-3-2', 'brk-3-4-1', 'brk-3-4-2') </script> <td class = "repcolrow" style = "text-align: right;; vertical-align:top; padding-top: 10px color:630D85 " > <a class = "repbordtop" style = "position:relative; top:4px"> 500.00 </a> </td> <td class = "repcolrow" style = "text-align: left;; vertical-align:top; padding-top: 10px color:630D85 " > <a class = "repbordtop" style = "position:relative; top:4px"> </a> </td> <tr> <td class = 'repsubf' style = "font-weight:bold"> Report Total : <br> <a class = "repnum" id = "cnt-4-1" style = ""> Count : </a> <a class = "repnum" id = "cnt-4-2" style = "; ">1 </a> </p> </td> <td class = "repcolrow" style = "text-align: left;font-weight:bold; vertical-align:top; padding-top: 10px color:630D85 " > <a class = "repbordtop" style = "position:relative; top:4px"> </a> </td> <script> placecount('cnt-4-1','cnt-4-2', 'brk-4-4-1', 'brk-4-4-2') </script> <td class = "repcolrow" style = "text-align: right;font-weight:bold; vertical-align:top; padding-top: 10px color:630D85 " > <a class = "repbordtop" style = "position:relative; top:4px"> 500.00 </a> </td> <td class = "repcolrow" style = "text-align: left;font-weight:bold; vertical-align:top; padding-top: 10px color:630D85 " > <a class = "repbordtop" style = "position:relative; top:4px"> </a> </td> <tr> <tr><td> </td></tr><table>
</cfsavecontent>
<cfset content = ReplaceNoCase(content,"{{d",date)>
<cfset content = ReplaceNoCase(content,"{{h",header)>
<cfset content = ReplaceNoCase(content,"{{r",report)>
<cfoutput>
#content#
</cfoutput>

Related

Rendering a dictionary in a template

While rendering values of a dictionary in a template, some values are showed outside the html table. I cant realize why.
Any ideas?
Thanks in advance,
#This is how the dictionary is printed in console
[{'socio': 'Randazzo Walter Ariel 25', 'enero': 'P', 'febrero': 'P', 'marzo': 'P', 'abril': 'P', 'mayo': 'P', 'junio': 'P', 'julio': 'P', 'agosto': 'P', 'septiembre': 'P', 'octubre': 'P', 'noviembre': 'P', 'diciembre': 'P'}, {'socio': 'Silvi Edgardo Marcelo 31', 'enero': 'P', 'febrero': 'P', 'marzo': 'P', 'abril': 'P', 'mayo': 'P', 'junio': 'P', 'julio': '-', 'agosto': '-', 'septiembre': '-', 'octubre': '-', 'noviembre': '-', 'diciembre': '-'}]
#this is how the template is rendered
#Template:
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Listados</title>
<style>
* {
color: black;
}
body {
font-family: "Roboto", "Lucida Grande", Verdana, Arial, sans-serif;
padding: 0;
margin: 0;
color: black;
}
.name-company {
font-size: 30px;
padding: 0;
margin: 0;
font-weight: bold;
text-transform: uppercase;
text-align: center;
}
table thead tr th {
border: 1px solid black !important;
padding: 3px;
}
table tbody tr td {
border: 1px solid black;
padding: 3px;
}
.img-logo {
margin-top: 10px;
width: 75px;
height: 75px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<img src="{{ icon }}" width="140" height="32" style="text-align: right;">
<p style="text-align: right;margin-top: 2px;">
</p>
<br>
<p style="text-align: left;margin-top: 2px;">
Año: {{ano}}
</p>
<br>
<div class="container-fluid">
<table class="table" style="width: 100%;">
<thead>
<tr style="border: 1px solid black;">
<th style="width: 30%; text-align: center;">SOCIO</th>
<th style="width: 25%; text-align: center;">ENE</th>
<th style="width: 25%; text-align: center;">FEB</th>
<th style="width: 25%; text-align: center;">MAR</th>
<th style="width: 25%; text-align: center;">ABR</th>
<th style="width: 25%; text-align: center;">MAY</th>
<th style="width: 25%; text-align: center;">JUN</th>
<th style="width: 25%; text-align: center;">JUL</th>
<th style="width: 25%; text-align: center;">AGO</th>
<th style="width: 25%; text-align: center;">SEP</th>
<th style="width: 25%; text-align: center;">OCT</th>
<th style="width: 25%; text-align: center;">NOV</th>
<th style="width: 25%; text-align: center;">DIC</th>
</tr>
</thead>
<tbody>
{% for pago in pagos %}
<tr {% if forloop.first %}style="padding-top: 3px;" {% endif %}>
<td class="text-center">{{ pago.socio }}</td>
<td class="text-center">{{ pago.enero }}</td>
<td class="text-center">{{ pago.febrero }}</td>
<td class="text-center">{{ pago.marzo }}</td>
<td class="text-center">{{ pago.abril }}</td>
<td class="text-center">{{ pago.mayo }}</td>
<td class="text-center">{{ pago.junio }}</td>
<td class="text-center">{{ pago.julio }}</td>
<td class="text-center">{{ pago.agosto }}</td>
<td class="text-center">{{ pago.septiembre }}</td>
<td class="text-center">{{ pago.octubre }}</td>
<td class="text-center">{{ pago.noviembre }}</td>
<td class="text-center">{{ pago.diciembre }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
#view
def get(self,request,*args,**kwargs):
anolistado = self.kwargs['ano']
listainfopagosanual=[]
sociosdet=[]
#devuelve el numero de socio
def numerodesocio(soc):
nrosocio=""
for c in soc:
if c.isnumeric():
nrosocio+=c
return nrosocio
#Lista de socios con pagos
pagosdet=PagosDetail.objects.all().select_related('pago').filter( ano_pago=anolistado).order_by('pago__numero_socio__numero_socio')
for det in pagosdet:
if str(det.pago.numero_socio) not in sociosdet:
sociosdet.append(str(det.pago.numero_socio))
#Por cada socio guardo los meses pagos
for soc in sociosdet:
nrosocio=numerodesocio(soc)
pagosdet1=PagosDetail.objects.all().select_related('pago').filter( ano_pago=anolistado,pago__numero_socio=nrosocio)
EneroPago="-";FebreroPago="-";MarzoPago="-";AbrilPago="-";MayoPago="-";JunioPago="-";JulioPago="-";AgostoPago="-";SeptiembrePago="-";OctubrePago="-";NoviembrePago="-";DiciembrePago="-"
for det in pagosdet1:
mespago=str(det.mes_pago)
if mespago=="Enero":
EneroPago="P"
if mespago=="Febrero":
FebreroPago="P"
if mespago=="Marzo":
MarzoPago="P"
if mespago=="Abril":
AbrilPago="P"
if mespago=="Mayo":
MayoPago="P"
if mespago=="Junio":
JunioPago="P"
if mespago=="Julio":
JulioPago="P"
if mespago=="Agosto":
AgostoPago="P"
if mespago=="Septiembre":
SeptiembrePago="P"
if mespago=="Octubre":
OctubrePago="P"
if mespago=="Noviembre":
NoviembrePago="P"
if mespago=="Diciembre":
DiciembrePago="P"
listainfopagosanual.append({'socio':soc,'enero':EneroPago,'febrero':FebreroPago,'marzo':MarzoPago,'abril':AbrilPago,'mayo':MayoPago,'junio':JunioPago,'julio':JulioPago,'agosto':AgostoPago,'septiembre':SeptiembrePago,'octubre':OctubrePago,'noviembre':NoviembrePago,'diciembre':DiciembrePago})
print (listainfopagosanual)
try:
template= get_template('socios/invoice_socioscuotas_anual.html')
context={
'ano': anolistado,
'pagos': listainfopagosanual,
'icon': '{}{}'.format(settings.STATIC_URL,'core/img/adicrareng.jpg'),
}
html=template.render(context)
response= HttpResponse(content_type='application/pdf')
pisaStatus=pisa.CreatePDF(html, dest=response,link_callback=self.link_callback)
return response
except Exception as ex:
print(ex)
return HttpResponse(reverse_lazy('pagos:list'))
#Models
class Socios(models.Model):
numero_socio = models.AutoField(primary_key=True)
nombre = models.CharField(max_length=50)
apellido = models.CharField(max_length=50)
tipo_documento = models.CharField(max_length=3, choices=tipos_documento, default ='DNI')
documento = models.CharField(max_length=50)
fecha_nacimiento = models.DateField(null=True,blank=True)
nacionalidad = models.CharField(max_length=50)
status = models.CharField(max_length=1,choices=lista_status,default='Activo')
domicilio = models.CharField(max_length=50)
localidad = models.CharField(max_length=50)
provincia = models.CharField(max_length=2, choices=lista_provincia, default ='2')
codigo_postal = models.CharField(max_length=50)
celular = models.CharField(max_length=50)
telefono_fijo = models.CharField(max_length=50, null=True)
twitter = models.CharField(max_length=50, null=True)
facebook = models.CharField(max_length=100, null=True)
linkedin = models.CharField(max_length=100, null=True)
fecha_ingreso = models.DateField(default=datetime.now,null=False,blank=False)
email = models.EmailField(null=True)
titulo = models.CharField(max_length=100,null=True)
institucion = models.CharField(max_length=150,null=True)
class PagosHead(models.Model):
numero_pago = models.IntegerField()
numero_socio = models.ForeignKey(Socios, on_delete=models.CASCADE)
fecha_pago = models.DateField(default=datetime.now,null=True,blank=True)
importe_pago_total = models.DecimalField(default=0.00,max_digits=9,decimal_places=2)
observaciones_pago = models.CharField(max_length=100,null=True)
numero_factura=models.CharField(max_length=14,default="00000-00000000",null=True,blank=True)
class PagosDetail(models.Model):
pago=models.ForeignKey(PagosHead,on_delete=models.CASCADE)
importe_pago = models.DecimalField(default=0.00,max_digits=9,decimal_places=2)
mes_pago = models.CharField(max_length=10)
ano_pago = models.SmallIntegerField(null=True)
#Final Rendered html Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Listados</title>
<style>
* {
color: black;
}
body {
font-family: "Roboto", "Lucida Grande", Verdana, Arial, sans-serif;
padding: 0;
margin: 0;
color: black;
}
.name-company {
font-size: 30px;
padding: 0;
margin: 0;
font-weight: bold;
text-transform: uppercase;
text-align: center;
}
table thead tr th {
border: 1px solid black !important;
padding: 3px;
}
table tbody tr td {
border: 1px solid black;
padding: 3px;
}
.img-logo {
margin-top: 10px;
width: 75px;
height: 75px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<img src="/static/core/img/adicrareng.jpg" width="140" height="32" style="text-
align: right;">
<p style="text-align: right;margin-top: 2px;">
</p>
<br>
<p style="text-align: left;margin-top: 2px;">
Año: 2020
</p>
<br>
<div class="container-fluid">
<table class="table" style="width: 100%;">
<thead>
<tr style="border: 1px solid black;">
<th style="width: 30%; text-align: center;">SOCIO</th>
<th style="width: 25%; text-align: center;">ENE</th>
<th style="width: 25%; text-align: center;">FEB</th>
<th style="width: 25%; text-align: center;">MAR</th>
<th style="width: 25%; text-align: center;">ABR</th>
<th style="width: 25%; text-align: center;">MAY</th>
<th style="width: 25%; text-align: center;">JUN</th>
<th style="width: 25%; text-align: center;">JUL</th>
<th style="width: 25%; text-align: center;">AGO</th>
<th style="width: 25%; text-align: center;">SEP</th>
<th style="width: 25%; text-align: center;">OCT</th>
<th style="width: 25%; text-align: center;">NOV</th>
<th style="width: 25%; text-align: center;">DIC</th>
</tr>
</thead>
<tbody>
<tr style="padding-top: 3px;" >
<td class="text-center">Randazzo Walter Ariel 25</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
</tr>
<tr >
<td class="text-center">Silvi Edgardo Marcelo 31</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">P</td>
<td class="text-center">-</td>
<td class="text-center">-</td>
<td class="text-center">-</td>
<td class="text-center">-</td>
<td class="text-center">-</td>
<td class="text-center">-</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
I have modified a the structure of the data from list of dictionaries to a dictionary.
#Now This is how the dictionary is printed in console
{'25': {'socio': 'Randazzo Walter Ariel 25', 'enero': 'P', 'febrero': 'P', 'marzo': 'P', 'abril': 'P', 'mayo': 'P', 'junio': 'P', 'julio': 'P', 'agosto': 'P', 'septiembre': 'P', 'octubre': 'P', 'noviembre': 'P', 'diciembre': 'P'}, '31': {'socio': 'Silvi Edgardo Marcelo 31', 'enero': 'P', 'febrero': 'P', 'marzo': 'P', 'abril': 'P', 'mayo': 'P', 'junio': 'P', 'julio': '-', 'agosto': '-', 'septiembre': '-', 'octubre': '-', 'noviembre': '-', 'diciembre': '-'}}
This is how I populate the dictionary:
dictinfopagosanual[nrosocio]={'socio':soc,
'enero':EneroPago,
'febrero':FebreroPago,
'marzo':MarzoPago,
'abril':AbrilPago,
'mayo':MayoPago,
'junio':JunioPago,
'julio':JulioPago,
'agosto':AgostoPago,
'septiembre':SeptiembrePago,
'octubre':OctubrePago,
'noviembre':NoviembrePago,
'diciembre':DiciembrePago,
}
Then I render in the template as follow:
<tbody>
{% for key,value in pagos.items %}
<tr {% if forloop.first %}style="padding-top: 3px;" {% endif %}>
{% for key,value in value.items %}
<td class="text-center">{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>

xhtml2pdf - Problem with displaying table rows using django forloop tag

What I am trying to do is to create an invoice pdf file with several table rows. Table rows would be created using for loop in Django. The problem is data inside for loop tag is not visible on the pdf file.
You can check the screenshots below. Django properly renders invoice.html template so the code is valid, but the pdf file contains empty frame without any table rows. To render pdf from html I am using xhtml2pdf.
how django render the invoice.html template
how pdf file looks like
invoice.html
<html>
<head>
{% load static %}
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="UTF-8">
<style>
#font-face {
font-family: Roboto;
src: url('{% static 'fonts/Roboto-Regular.ttf' %}');
}
#font-face {
font-family: Roboto-bold;
src: url('{% static 'fonts/Roboto-Bold.ttf' %}');
font-weight: bold;
}
#page {
size: a4 portrait;
#frame header_frame { /* Static Frame */
-pdf-frame-content: frame_header_left;
left: 50pt; width: 245pt; top: 30pt; height: 150pt;
}
#frame header_frame { /* Static Frame */
-pdf-frame-content: frame_header_right;
left: 300pt; width: 245pt; top: 50pt; height: 150pt;
}
#frame content_frame { /* Content Frame */
-pdf-frame-content: frame_invoice_number;
left: 50pt; width: 512pt; top: 170pt; height: 30pt;
}
#frame col1 {
-pdf-frame-content: frame_col1;
left: 50pt; width: 245pt; top: 220pt; height: 130pt;
}
#frame col2 {
-pdf-frame-content: frame_col2;
left: 300pt; width: 245pt; top: 220pt; height: 130pt;
}
#frame frame_services {
-pdf-frame-content: frame_services;
left: 50pt; width: 512pt; top: 380pt; height: 250pt;
-pdf-frame-border: 1;
}
#frame content_frame {
-pdf-frame-content: frame_summary;
left: 465pt; width: 100pt; top: 590pt; height: 50pt;
}
#frame content_frame {
-pdf-frame-content: frame_vat;
left: 50pt; width: 512pt; top: 590pt; height: 150pt;
}
#frame content_frame {
-pdf-frame-content: frame_signatures_left;
left: 50pt; width: 140pt; top: 725pt; height: 70pt;
}
#frame content_frame {
-pdf-frame-content: frame_signatures_right;
left: 400pt; width: 140pt; top: 725pt; height: 70pt;
left: 400pt; width: 140pt; top: 725pt; height: 70pt;
}
#frame content_frame {
-pdf-frame-content: footer_content;
left: 50pt; width: 512pt; top: 775pt; height: 50pt;
}
}
body {
background-color: white;
font-family: "Roboto", sans-serif;
}
.right{
font-size: 10px;
text-align: right;
}
.left{
text-align: left;
}
.invoice-number {
font-size: 18px;
font-family: "Roboto-bold", sans-serif;
}
.col-titles {
font-size: 16px;
text-decoration: underline;
font-family: "Roboto-bold", sans-serif;
}
.footer {
font-size: 8px;
text-align: center;
}
p{
font-size: 10px;
line-height: 0;
}
table {
border-bottom: 1px solid #ddd;
text-align: center;
}
td, td {
border-bottom: 1px solid #ddd;
vertical-align: middle;
}
.summary{
border-bottom: 1px solid #ddd;
}
.signatures {
border-top: 1px solid black;
font-size: 8px;
text-align: center;
}
th {
height: 36px;
}
td {
height: 25px;
}
</style>
</head>
<body>
<div>
<div>
<div id="frame_header_left" class="left">
<img src="{% static 'invoices/logo.png' %}" alt="logo" width="150" height="112">
</div>
<div id="frame_header_right" class="right">
<p>Miejsce wystawienia: Żabno</p>
<p>Data badania: {{ invoice.data_badania }}</p>
<p>Data wystawienia: {{ invoice.data_wystawienia_faktury }}</p>
</div>
</div>
<div id="frame_invoice_number">
<div class="invoice-number">
<h2>Faktura nr: {{ invoice.numer }}</h2>
</div>
</div>
<div id="frame_col1">
<p class="col-titles">Sprzedawca</p>
<div>
<p>MEDIKAP</p>
<p>ul. Plac Grunwaldzki 15B, 33-240 Żabno</p>
<p>NIP: 999999999</p>
<p>REGON: 9999999</p>
<p>Bank: ING Bank Śląski</p>
<p>Nr konta: 12 1234 1234 1243 1243 214 1244</p>
</div>
</div>
<div id="frame_col2">
<p class="col-titles">Nabywca</p>
<div>
<p> {{ invoice.firma}} </p>
<p> ul. {{ invoice.firma.ulica }} </p>
<p> {{ invoice.firma.kod_pocztowy }} {{ invoice.firma.miasto}}</p>
<p> NIP: {{ invoice.firma.nip }}</p>
<p> REGON: {{ invoice.firma.regon }}</p>
<p> forma płatności: {{ invoice.get_forma_platnosci_display}}</p>
</div>
</div>
<div id="frame_services">
<table>
<tr>
<th style="width: 50px;"> # </th>
<th style="width: 600px;"> Nazwa usługi</th>
<th style="width: 100px;"> Ilość</th>
<th style="width: 100px;"> Rabat[%]</th>
<th style="width: 100px;"> Cena usługi</th>
<th style="width: 100px;"> Wartość</th>
<th style="width: 100px;"> Wartość z rabatem:</th>
</tr>
{% for service in services_items %}
<tr>
<td> test </td>
<td> test </td>
</tr>
{% endfor %}
</table>
</div>
<div id="frame_summary" class="summary">
<p> : {{ service.get_total_value }} PLN</p>
<p> Wartość z uwzględnieniem {{ invoice.rabat}}% rabatu: {{ discounted_value|floatformat:"-2" }} PLN</p>
</div>
<div id="frame_vat">
<p> Podstawa zwolnienia z VAT: </p>
<p> Zwolnienie ze względu na zakres wykonywanych czynności (art. 43 ust.1) pkt 19 Ustawy o VAT</p>
</div>
<div id="frame_signatures_left">
<p class="signatures"> podpis osoby upoważnionej do odbioru faktury</p>
</div>
<div id="frame_signatures_right">
<p class="signatures"> podpis osoby upoważnionej do wystawienia faktury</p>
</div>
<div id="footer_content" >
<p class="footer">MEDIKAP Maria K.</p>
<p class="footer">Plac Grunwaldzki 15B, 33-240 Żabno</p>
<p class="footer">e-mail: gabinet.medikap#gmail.com tel: 539 993 332</p>
<p class="footer">NIP: 9930212793 REGON: 852441210</p>
</div>
</div>
</body>
</html>
views.py/DetailsInvoice
class DetailsInvoice(generic.View):
template_name = 'invoices/invoice_detail.html'
form_class = DetailInvoiceForm
success_url = reverse_lazy("invoices:list")
def get(self, request, invoice_id):
current_invoice = get_object_or_404(Invoice, id=invoice_id)
form = self.form_class(instance=current_invoice)
request.session['invoice_id'] = current_invoice.id
services = Service.objects.all()
all_service_items = ServiceItem.objects.all().filter(faktura = current_invoice).order_by('usluga')
context = {
'invoice': current_invoice,
'form' : form,
'services' : services,
'services_items' : all_service_items,
}
return render(request, self.template_name, context)
def post(self, request, invoice_id):
current_invoice = get_object_or_404(Invoice, id=invoice_id)
form = self.form_class(request.POST, instance=current_invoice)
all_service_items = ServiceItem.objects.all().filter(faktura=current_invoice)
context = {
'invoice' : current_invoice,
}
pdf = render_to_pdf('invoices/invoice.html', context)
services_assigned_to_invoice = current_invoice.uslugi.all()
if 'update-data' in request.POST and form.is_valid():
for service in all_service_items:
service_item = get_object_or_404(ServiceItem, id=service.id)
quantity_input = request.POST.get('quantity-' + str(service.id))
discount_input = request.POST.get('discount-' + str(service.id))
service_item.ilosc = int(quantity_input)
service_item.rabat = int(discount_input)
service_item.save()
form.save()
for service_item in all_service_items:
if service_item.usluga not in services_assigned_to_invoice:
service_item.delete()
for single_service in services_assigned_to_invoice:
new_service_item, created = ServiceItem.objects.get_or_create(usluga=single_service, faktura=current_invoice)
messages.success(request, 'Pomyślnie zaktualizowane dane')
return HttpResponseRedirect(self.request.META.get('HTTP_REFERER'))
if 'view-pdf' in request.POST:
return HttpResponse(pdf, content_type='application/pdf')
if 'download-pdf' in request.POST:
response = HttpResponse(pdf, content_type='application/pdf')
filename = f"Faktura {current_invoice.numer}.pdf"
content = "attachment; filename={}".format(filename)
response['Content-Disposition'] = content
return response
else:
return redirect('invoices:list')
rendering function
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result, link_callback=link_callback)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
You are not passing the same context variables to your PDF as the ones you are passing to your HTML template. To your HTML template you are passing:
context = {
'invoice': current_invoice,
'form' : form,
'services' : services,
'services_items' : all_service_items,
}
While to your PDF you are only passing:
context = {
'invoice' : current_invoice,
}
services_items is the one your PDF template seems to be missing. So because for service in services_items is an empty/non-existent list in your PDF template, it doesn't render any rows. In the future you can check this by adding an {% empty %} section to your for loop:
{% for service in services_items %}
<tr>
<td> test </td>
<td> test </td>
</tr>
{% empty %}
No items!
{% endfor %}

I need to display a python array in angular

This is the array
[
{
"TO":"test#gmail.com",
"FROM":"nathanoluwaseyi#gmail.com",
"SUBJECT":"subject 1",
"NAME":"Oluwaseyi Oluwapelumi",
"MESSAGE-DATE":[
[
"Hey eniayomi heeyyy",
"2019-12-03 20:49:07"
]
]
},
{
"TO":"test#gmail.com",
"FROM":"pelz#gmail.com",
"SUBJECT":"Thanks for contacting R",
"NAME":"",
"MESSAGE-DATE":[
[
"Thanks for contacting me! Once i check my email, i shall definitely get back.",
"2019-08-18 19:48:10"
],
[
"will check it.",
"2019-08-18 19:48:10"
]
]
}
]
i need it to display on the angular frontend.
this is the mail.component.html file
<div class="card-body p-0">
<div class="float-left" style="width: 330px; height: 430px; border-right: 1px solid #dad9d9; overflow-x: hidden; overflow-y: auto;">
<div class="p-2 profile-card" style="width: 315px; height: 100px; border-bottom: 1px solid #dad9d9;" *ngFor="let mail of dataservice.data; let i = index;" (click)="viewMail(mail.MESSAGE_DATE,mail.FROM,mail.NAME,mail.DATE,i)" [ngClass]="{'highlight': selectedIndex === i}">
<div class="row">
<div class="col-md-3 pt-2">
<div class="rounded-circle shadow" style="background-image: url('images/avt.jpg'); background-repeat: round; height: 70px; width: 70px;">
<div style="height: 20px; width: 20px; border: 3px solid white;" class="rounded-circle bg-success"></div>
</div>
</div>
<div class="col-md-7 p-0 pl-3 pt-4" style="line-height: 12px;">
<p style="font-size:18px;"><b>{{mail.FROM}}</b></p>
<p style="font-size:13px;">{{mail.NAME }}.</p>
</div>
<div class="col-md-2 p-0 pt-3" style="line-height:11px;">
<p class="text-secondary" style="font-size:12px;">20m <i class="fa fa-star fa-md" aria-hidden="true"></i></p>
</div>
</div>
</div>
this is the data.service.ts file
mail_det() {
this.message = 'Welcome!';
console.log(this.message);
this.staff_email=sessionStorage.getItem('email');
console.log(this.staff_email)
this.http.get(this.domain_protocol + this.f_domain_name+'/api/v1.0/get_user_detail/?id='+this.staff_email)
.subscribe((res) => {
this.data = res
console.log(this.data)
})
}
this is the mail.component.ts file
viewMail(mail, mailer, mailee, user_date, _index: number) {
this.router.navigate(['mail/'+ mailer])
console.log(mail)
console.log(mailer)
console.log(user_date)
this.message = ''
sessionStorage.setItem('mailer', mailer)
sessionStorage.setItem('mailee', mailee);
sessionStorage.setItem('user_date', user_date)
console.log(sessionStorage.getItem('mailer'))
this.user_message = mail;
this.mailee = mailee;
this.user_date = user_date;
this.selectedIndex = _index;
}
i am doing something wrong. The only thing i get to show is the mail.FROM and mail.SUBJECT. I know this is because of the array in the mesage part. I dont know how to go about that.
In Data.service.ts
mail_det() {
this.message = 'Welcome!';
console.log(this.message);
this.staff_email=sessionStorage.getItem('email');
console.log(this.staff_email)
this.http.get(this.domain_protocol + this.f_domain_name+'/api/v1.0/get_user_detail/?id='+this.staff_email);
}
in mail.component.ts
public data: Array<any> = [];
constructor(public dataSrv: DataService <-- this is the class name of the data service you created; import it)
ngOnInit(){
this.dataSrv.mail_det().subscribe(result =>{
console.log(result); <-- your api response;
this.data = result;
}, error => {console.log(error);
});
}
in mail.component.html
<div class="card-body p-0">
<div class="float-left" style="width: 330px; height: 430px; border-right: 1px solid #dad9d9; overflow-x: hidden; overflow-y: auto;">
<div class="p-2 profile-card" style="width: 315px; height: 100px; border-bottom: 1px solid #dad9d9;" *ngFor="let mail of data; let i = index;" (click)="viewMail(mail.MESSAGE_DATE,mail.FROM,mail.NAME,mail.DATE,i)" [ngClass]="{'highlight': selectedIndex === i}">
<div class="row">
<div class="col-md-3 pt-2">
<div class="rounded-circle shadow" style="background-image: url('images/avt.jpg'); background-repeat: round; height: 70px; width: 70px;">
<div style="height: 20px; width: 20px; border: 3px solid white;" class="rounded-circle bg-success"></div>
</div>
</div>
<div class="col-md-7 p-0 pl-3 pt-4" style="line-height: 12px;">
<p style="font-size:18px;"><b>{{mail.FROM}}</b></p>
<p style="font-size:13px;">{{mail.NAME }}.</p>
</div>
<div class="col-md-2 p-0 pt-3" style="line-height:11px;">
<p class="text-secondary" style="font-size:12px;">20m <i class="fa fa-star fa-md" aria-hidden="true"></i></p>
</div>
</div>
</div>

How do I get the value of CharField() during instansiation?

I want to pass model fields values as arguments to another field.
trademark_class.get_default() method is close to what I want, but I do not want solely the default value.
I am also unable to use __dict__.['trademark_class'] in this case as I need a 'this' reference to the class and do not know the proper way to achieve that for this case.
class Form_33_Model(models.Model):
trademark_number = models.CharField(default='default number', max_length=30)
trademark_class = models.CharField(default='default class', max_length=30)
trademark_date = models.DateField(default=datetime.date.today)
html = models.TextField(default=Form33StringClass(trademark_class=trademark_class.get_default(),
trademark_number=trademark_number.get_default()).form_33_string)
Instead of the default value only, I would like to get either the actual value of the Charfield or its default value.
So something like : trademark_class.get_current_value_or_default() would be ideal for what I want.
Below is my Form33StringClass.py
import datetime
class Form33StringClass():
def __init__(self, trademark_number, trademark_class):
self.trademark_number = trademark_number
self.trademark_class = trademark_class
self.day = datetime.datetime.now().strftime("%A") + " " + datetime.datetime.now().strftime("%d")
self.month = datetime.datetime.now().strftime("%B")
self.year = datetime.datetime.now().strftime("%Y")
self.form_33_string = """
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Trade Marks Act</title>
<style>
.letter_margin {
margin: auto 25%;
line-height: 25px;
}
header{
text-align: center;
}
.intro {
text-align: center;
font-style: italic;
}
.request{
}
.office_address{
width: 50%;
margin-left: 10%;
}
.address_row{
display: flex;
align-items: baseline;
}
.re-address_row{
/* float: right; */
display: flex;
justify-content: flex-end;
}
.re_address{
width: 60%;
}
.to_registrar{
display: flex;
align-items: baseline;
}
.registrar_paragraph {
margin-left: 10%;
}
.underlined{
text-decoration: underline;
}
.trademark_class{
}
.trademark_number{
}
</style>
</head>
<body>
<table>
<tr>
<header>
<h1>TRADE MARKS ACT</h1>
<h2>FORM 33</h2>
</header>
</tr>
<tr >
<div class="intro letter_margin">
<p>
Form of Request to the Registrar by a Registered Proprietor or a Registered User of a Trade Mark, or a person about to be so registered, to enter, alter, or substitute an Address for service as part of his Registration (Regulations 15, 82. 86 and 102)
</p>
</div>
</tr>
<tr>
<div class="request letter_margin">
<p >
Request is made by: <br><br>
A company incorporated in <br>
Carrying on business as manufacturers and merchants at:<br><br><br>
who is about to be registered as/who is the Registered Proprietor of Trade Mark(s)<br> No <span class="underlined trademark_number"> """+ trademark_number +"""</span> registered in Class(es) <span class="underlined trademark_class"> """+trademark_class+"""</span> <br>
for the inclusion/addition/alteration/substitution of an address for service in Nigeria in or to <br> the entry thereof so that the address for service in Nigeria may read:
</p>
</div>
</tr>
....
</body>
</html>
"""
when a new Form_33_Model.objects.create(trademark_class, trademark_number) is created :
{
trademark_class : "class foo",
trademark_number : "number bar",
html : "<html>...
<tag> class foo </tag>
<tag> number bar </tag>
...
</html>"
}
I still can't really understand what you are trying to do. But perhaps SerializerMethodField is what you want?
class Form33ModelSerializer(serializers.ModelSerializer):
html = SerializerMethodField()
class Meta:
model = Form_33_Model
def get_html(self, obj):
return obj.html or obj._meta.get_field('trademark_class').get_default()
I solved my problem in the end by overriding the save() method in the model.
class Form_33_Model(models.Model):
trademark_number = models.CharField(default='default number', max_length=30)
trademark_class = models.CharField(default='default class', max_length=30)
trademark_date = models.DateField(default=datetime.date.today)
html = models.TextField(default=Form33StringClass(
trademark_class=trademark_class.get_default(),
trademark_number=trademark_number.get_default()
).form_33_string)
def save(self, *args, **kwargs):
self.html = Form33StringClass(
trademark_class=self.trademark_class,
trademark_number=self.trademark_number
).form_33_string
super(Form_33_Model, self).save(*args, **kwargs)

Knockoutjs list in a list select binding

I have seen so many example of this problem but not as a list. Here's my code:
<div>
<form>
<p>You have asked for <span data-bind='text: gifts().length'> </span> gift(s)</p>
<input id='giftname' type='text'/><button data-bind='click: createGift'>Add Gift</button>
<table>
<thead>
<tr>
<th>Gift name</th>
<th>Pack</th>
<th>Price</th>
<th />
</tr>
</thead>
<tbody data-bind='foreach: gifts'>
<tr>
<td><input data-bind='value: name' readonly='readonly'/></td>
<td><select data-bind="options: packs,
optionsText: 'pack',
value: price" /></td>
<td><input data-bind="value: price ? price.packprice : 'unknown'" readonly="readonly"/></td>
<td><a href='#' data-bind='click: $root.removeGift'>Delete</a></td>
</tr>
</tbody>
</table>
<button data-bind='enable: gifts().length > 0' type='submit'>Submit</button>
</form>
</div>
<script type="text/javascript">
var GiftModel = function(gifts) {
var self = this;
self.gifts = ko.observableArray(gifts);
self.addGift = function(gift) {
var newGift = {
name: gift.name,
packs: gift.packs,
price: gift.price
};
self.gifts.push(newGift);
};
self.removeGift = function(gift) {
self.gifts.remove(gift);
};
self.createGift = function() {
var gname = $('#giftname').val();
//should be getting gift options from webservice
var newGift = {name: gname,
packs: [{pack:'Each', packprice: '2'}, {pack:'Dozen', packprice: '12'}], price: {pack:'', packprice: ''}};
self.addGift(newGift);
$('#giftname').val('');
};
};
var viewModel = new GiftModel([]);
ko.applyBindings(viewModel);
</script>
When I add gifts, it creates options of packs. Each pack has a certain price. My problem is just simple. How will I show the price on the next column for the selected pack of the gift line? Sorry im just new to knockoutjs. Thanks!
System will automatically update price after selecting package if you make it observable. I made a little refactoring to you code, now it works:
<div>
<form>
<p>You have asked for <span data-bind='text: gifts().length'> </span> gift(s)</p>
<input
id='giftname' type='text' data-bind='value: giftName' />
<button data-bind='click: createGift'>Add Gift</button>
<table>
<thead>
<tr>
<th>Gift name</th>
<th>Pack</th>
<th>Price</th>
<th />
</tr>
</thead>
<tbody data-bind='foreach: gifts'>
<tr>
<td>
<input data-bind='value: name' readonly='readonly' />
</td>
<td>
<select data-bind="options: packs,
optionsText: 'pack',
optionsValue: 'packprice',
value: price" />
</td>
<td>
<input data-bind="value: price() || 'unknown'" readonly="readonly"
/>
</td>
<td><a href='#' data-bind='click: $root.removeGift'>Delete</a>
</td>
</tr>
</tbody>
</table>
<button data-bind='enable: gifts().length > 0' type='submit'>Submit</button>
</form>
</div>
function GiftModel(name) {
var self = this;
self.name = ko.observable(name);
self.price = ko.observable();
self.packs = ko.observable([{
pack: 'Each',
packprice: '2'
}, {
pack: 'Dozen',
packprice: '12'
}]);
}
var ViewModel = function (gifts) {
var self = this;
self.gifts = ko.observableArray(gifts);
self.giftName = ko.observable();
self.removeGift = function (gift) {
self.gifts.remove(gift);
};
self.createGift = function () {
self.gifts.push(new GiftModel(self.giftName()));
};
};
var viewModel = new ViewModel([]);
ko.applyBindings(viewModel);
Here is working fiddle: http://jsfiddle.net/vyshniakov/pzJaH/
P.S. Don't use jQuery to get field value if you using knockout. It is much easier to do this with knockout.