Theophilus Ngaribvume

This is Where i Share my Experiences, Ideas, and Thoughts. One Post a Day.


Django Models Save Images From Remote URLs

25 October, 2021 - 2 min read

This is on django saving images from a remote url or link. Imagine you're curating content from multiple news sources and you need to auto fetch posts and save images from the source image urls. In recent weeks i was building such a django app and i needed a way to save images into django media as i save those curated posts. In case you have the same needs, this is how you do it:

# models.py file #Other models.py imports from django.utils.translation import ugettext as _ from tinymce import models as tinymce_models from django.template.defaultfilters import slugify from django.core.files import File from urllib.request import urlopen from tempfile import NamedTemporaryFile import os class Post(models.Model): title = models.CharField(_("Title"), max_length=100) published = models.DateTimeField(_("Date published")) source = models.ForeignKey( "news.Source", verbose_name=_(""), on_delete=models.CASCADE) excerpt = tinymce_models.HTMLField(_("Article Excerpt")) content = tinymce_models.HTMLField(_("Article Content")) image_src = models.CharField( _("Image from Source"), null=True, blank=True, max_length=200) image = models.ImageField( _("Article Image"), null=True, blank=True, upload_to="news/posts") slug = models.SlugField(max_length=500, unique=True, null=True, blank=True) class Meta: verbose_name = _("Post") verbose_name_plural = _("Posts") def save(self, *args, **kwargs): string = "{}".format(self.title) slug = slugify(string) self.slug = slug if self.image_src and not self.image: img_temp = NamedTemporaryFile(delete=True) img_temp.write(urlopen(self.image_src).read()) img_temp.flush() filename, file_extension = os.path.splitext( self.image_src) self.image.save(f"{slug}{file_extension}", File(img_temp)) super(Post, self).save(*args, **kwargs)

This is all you need.

Happy coding !.

Creator of Workly and Nerdlify, Currently working at Pindula.

© 2021, Theophilus Ngaribvume. All Rights Reserved.