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

How to use robot.txt on a Django Website
How to use robot.txt on a Django Website
How to add a robots.txt file on a Django website so that you..
Read More
Top sites for remote jobs
Top sites for remote jobs
Where to find remote jobs for software developers in 2022...
Read More
Project ideas for a software developer portfolio
Project ideas for a software developer portfolio
Projects which can strengthen your portfolio as a software d..
Read More
My case for WordPress
My case for WordPress
WordPress strengths and weaknesses. When you should use Word..
Read More