Suppose, you have a File model, that is managing files for your django application and you want to have an easy way of obtaining an elements S3 bucket URL. How to do it?

Requirements

  • boto3 library
  • django-storage libraray
  • Django settings.py with AWS_STORAGE_BUCKET_NAME and AWS_S3_REGION_NAME set.

How to do it?

Just set up a post-saving hook and set the additional s3_link.

from django.db import models
from django.conf import settings
from django.db.models.signals import post_save

class File(models.Model):
    file = models.FileField()
    s3_link = models.CharField(max_length=128, default="", blank=True)

    def setS3Link(self):
        # e.g. https://s3.eu-central-1.amazonaws.com/your.bucket/2020/03/19/ea77999a-e683-40f6-8a7a-a26d471d7ec8.png
        self.s3_link = f"https://s3.{settings.AWS_S3_REGION_NAME}.amazonaws.com/{settings.AWS_STORAGE_BUCKET_NAME}/{self.file.name}"
        self.save()
        return True

def fileSaved(sender, instance, *args, **kwargs):
    instance.setS3Link()

post_save.connect(fileSaved, sender=File)

THEME_QUARK.BLOG.ITEM.PREV_POST THEME_QUARK.BLOG.ITEM.NEXT_POST