Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving BytesIO to Django ImageField

I have a web scraper that I want to download an image of the page it's scraping and save it as a "screenshot" ImageField in a Django model. I am using this code:

def save_screenshot(source,screenshot):
    box = (0, 0, 1200, 600)
    im = Image.open(io.BytesIO(screenshot))
    region = im.crop(box)
    tempfile_io = io.BytesIO()
    region.save(tempfile_io, 'JPEG', optimize=True, quality=70)
    source.screenshot.save(source.slug_name+"-screenshot",ContentFile(tempfile_io.getvalue()),save=True)

It saves the screenshot to the /media/news_source_screenshots/ directory but doesn't save it to the model. The model field is defined as:

screenshot = models.ImageField(upload_to='news_source_screenshots',blank=True,null=True)

What am I missing?

like image 542
Anthony Ainsworth Avatar asked Dec 30 '16 22:12

Anthony Ainsworth


1 Answers

So it turns out the above code works great! The issue was that I was calling the above method using a piece of code like this:

source = NewsSource.objects.get(name=name)
html,screenshot = get_url(source.url)
save_screenshot(source,screenshot)
source.save()

So the save_sceenshot method worked but then the work it had done was overwritten by my source.save() call. Go figure!

like image 69
Anthony Ainsworth Avatar answered Sep 28 '22 03:09

Anthony Ainsworth