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?
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.