Join Login Create a Request

Django save images from remote URL

|
Django save images from remote URL

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.


Tags.




Recent Posts

Ways to differentiate your services from others as a freelancer
Ways to differentiate your services from others as a freelancer
Ways to differentiate your services from others as a freelan..
Read More
Starting a referral or affiliate program as a freelancer.
Starting a referral or affiliate program as a freelancer.
How to start a referral program as a freelancer. These are s..
Read More
How to build referrals as a freelancer
How to build referrals as a freelancer
Ways to build your referrals as a freelancer. Expand your lo..
Read More
Handling customer Service as a Freelancer
Handling customer Service as a Freelancer
How to handle customer services as a freelancer. Learn the b..
Read More