I'm making use of FPDF in python to generate an invoice in PDF through a function. I build a table in HTML using a string variable and the loop through a list which has barcodes to populate the lines of the table tags.
The problem I'm having is that I keep getting this TypeError TypeError: string indices must be integers, not str
when I try and generate the PDF, this happens when the loop is entered and the HTML variable amended with the row HTML string.
Initial HTML variable with the table tags looks like this:
html = """<table border="0" align="left" width="100%"><thead><tr><th align="left" width="25%">Code</th><th align="left" width="25%">Title</th><th align="left" width="25%">Variant</th><th align="left" width="25%">Price</th></tr></thead><tbody>"""
Then the for loop looks like this, where it amends the <td>
rows to the table string variable:
for sku in _skus:
prod_info = finder(sku) #returns a JSON object from mongodb
html += "<tr><td>", str(prod_info['varsku']), "</td><td>", str(prod_info['prodtitle']), "</td><td>", str(prod_info['vartitle']), "</td><td>", str(prod_info['varprice']), "</td></tr>"
html += str("</tbody></table>")
pdf.write_html(html)
This is what prod_info looks like at this stage after coming from finder()
:
{"prodvendor": "Elpaso", "vartaxable": "false", "varquantity": "1", "varid": "33210590148", "varprice": "235.00", "prodtype": "Type1", "varcreated": "_varCreated", "prodtitle": "3 Way Cora Hols - Piol", "varsku": "102-10001-CRD-G19", "vartitle": "C P0 / Gk 19/23", "varoption": "C P0 / Gk 19/23", "_id": {"$oid": "58e77040da522f333c757852"}, "prodid": "9665780932"}
this is where I get the TypeError
.
I have tried to convert everything to string to patch the "string" variable but still, I get the TypeError.
Any help will be much appreciated.
{{ Update }}
def finder(_sku):
result = collection.find_one({"varsku":_sku})
if result == None:
return "None"
else:
return dumps(result)
I found the problem. It was with the way I construct the html
string variable.
When using a comma ,
in the variable it means the variables are seen as tuples: The comma ,
in the separation between string and variable indicates a tuple.
html += "<tr><td>", str(_code), "</td><td>", (_prodtitle), "</td>"
This means you are combining string:
html += "<tr><td>"+str(_code)+"</td><td>"+str(_prodtitle)+"</td>
It solved the TypeError: cannot concatenate 'str' and 'tuple' objects
problem.
And the below solved the initial TypeError: string indices must be integers, not str
problem.
prod_info = json.loads(finder(sku))
Thanks to this SO post and thanks to @el.pescado and @Ultcyber