Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add images to python docxtpl from url

Tags:

python

django

I have a docxtpl document, but I need to add images to the InlineImage from a url, not local disk.

I'm using Django

So this works (document is a DocxTemplate):

InlineImage(document,'C:/Users/sande/Pictures/myimage.png')

But how do i do this?:

InlineImage(document,'https://files-cdn.myhost.net/3255/ddef9d07-0a6b-4f54-801a-c016e6d41885/myimage.png')

the image_descriptior doesn't accept a url.:

Exception has occurred: OSError [Errno 22] Invalid argument:'https://files-cdn.myhost.net/3255/ddef9d07-0a6b-4f54-801a-c016e6d41885/myimage.png'

like image 468
Sander Avatar asked Oct 23 '25 09:10

Sander


1 Answers

I found out what to do:

In my model I added the following (I use a model with image urls in a char field called ImageURL)

from django.db import models
import requests
import io

class myModel(models.Model)
    ImageURL = models.CharField(max_length=250, null=True, blank=True)
    

    @property
    def product_image(self):
        "Returns the product image"
        response = requests.get(self.ImageURL)
        image_bytes = io.BytesIO(response.content)
        return image_bytes

You can use this property in the inlineimage class of docxtpl and it works

like image 98
Sander Avatar answered Oct 27 '25 00:10

Sander