I am doing a Django project that needs to receive an image and store it into the database as a TextField. To accomplish that I am doing something similar to this:
In my models.py:
class Template(models.Model):
image = models.TextField(null=True, blank=True)
The equivalent code is:
with open('logo.png', 'rb') as file:
image = str(file.read())
Template.objects.create(id=1, image=image)
Later, when I need to get back the file and convert it to base64 to insert in an HTML file, I am doing the following:
import base64
from django.template import Template as DjangoTemplate
from django.template import Context
from weasyprint import HTML
from .models import Template
template = Template.objects.get(id=1)
data = {'logo': base64.b64encode(str.encode(template.image)).decode('utf-8')}
html_template = DjangoTemplate(template.html_code)
html_content = html_template.render(Context(data)))
file = open('my_file.pdf', 'wb')
file.write(HTML(string=html_content, encoding='utf8').write_pdf())
file.close()
But the problem is that the image is not showing in the pdf file. I've also tried to copy the decoded data and open it with another site, but I got a broken file.
How can I fix my code to convert the image properly?