2

My question is not a duplicate of this question it is not related

Basically I got the following model where some uploaded documents will be public and some others private. To decide when the doc is private or not, when creating the instance, I set the field is_public=True/False, then I will be able to choose the right direction within the AWS S3 bucket. So I want to be able to change the storage to PrivateMediaStorage() when is_public=False

from my_project.storage_backends import PrivateMediaStorage

class Document(models.Model):
    file            = models.FileField(upload_to="uploaded_documents/%d-%m-%Y")
    # file          = models.FileField(upload_to="uploaded_documents/%d-%m-%Y",
    #                 storage=PrivateMediaStorage())
    uploaded_by     = models.ForeignKey(UserProfile,blank=True,null=True)
    nb_download     = models.IntegerField(default=0)

    is_public       = models.BooleanField(default=False)

Here is the storage class in case it's important.

from storages.backends.s3boto3 import S3Boto3Storage
from django.conf import settings

class PrivateMediaStorage(S3Boto3Storage):
    location = settings.AWS_PRIVATE_MEDIA_LOCATION
    default_acl = 'private'
    file_overwrite = False
    custom_domain = False
Eu Chi
  • 533
  • 1
  • 6
  • 22
  • Are the public files also stored on s3? Is it just a matter of changing the bucket? – RishiG Aug 31 '18 at 20:58
  • yes! I have two different locations with `AWS_PRIVATE_MEDIA_LOCATION` and `AWS_PUBLIC_MEDIA_LOCATION` – Eu Chi Aug 31 '18 at 21:07
  • I don't have time to try things out and give a full answer, but can you use an extension of [this proposed solution](https://stackoverflow.com/a/37061044/2715819)? – RishiG Aug 31 '18 at 21:12
  • hmm, nevermind... that's not really runtime dynamic – RishiG Aug 31 '18 at 21:17
  • yeah! I thought I could do something with it until I see the `self` in the class is the file, not the model instance – Eu Chi Aug 31 '18 at 21:18
  • ooh: I think I have a way in. Again I don't have time to really test it out, but if you use a dynamic filename generator in `upload_to`, you have access to the instance. You might be able to insert a filename prefix, then override the storage `save` to pluck the filename and adjust storage variables accordingly? – RishiG Aug 31 '18 at 21:23
  • thanks I will give it a try. – Eu Chi Aug 31 '18 at 21:33
  • Hi, how did you finally go about it ? – ImportError Nov 13 '21 at 03:04

0 Answers0