Audvik Labs

How to Fetch a file from URL & upload to FileField | Django

I have been working on Python and Django projects since 2014 and during my journey I had a requirement where I had to pull a signed pdf from a third-party server and save it in our S3 bucket. In order to do that I used the urlretrieve method from urllib.request library. I have shared a sample code below.

from django.core.files import File
from django.utils import timezone
from urllib.request import urlretrieve

class SignedFile(models.Model):
  Some other model variables
  signed_file = models.FileField(
    blank=True, null=True)
  def download_to_local(self, url):
    name, _ = urlretrieve(url)"{timestamp}.pdf".format('%Y-%m-%d%/%H-%M-%S')), File(open(name, 'rb')))

We can use urlcleanup after we have saved the file.

from urllib.request import urlretrieve, urlcleanup

def download_to_local(self, url):
    name, _ = urlretrieve(url)"{timestamp}.pdf".format('%Y-%m-%d%/%H-%M-%S')), File(open(tempname, 'rb')))

For Further more u can visit Django Documentation from here.

Leave a comment

Your email address will not be published. Required fields are marked *