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(
    upload_to="customer/signed/%Y-%m-%d%/%H-%M-%S/", 
    blank=True, null=True)
  
  def download_to_local(self, url):
    name, _ = urlretrieve(url)
    self.signed_file.save("{timestamp}.pdf".format(timestamp=timezone.now().strftime('%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):
  try:
    name, _ = urlretrieve(url)
    self.signed_file.save("{timestamp}.pdf".format(timestamp=timezone.now().strftime('%Y-%m-%d%/%H-%M-%S')), File(open(tempname, 'rb')))
  finally:
    urlcleanup()

For Further more u can visit Django Documentation from here.

Leave a comment

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