0
class StorageModel(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="profile", null=False)
    file_meta = models.ImageField(storage=UserDataStorage(profile=user), blank=False, null=False)



class UserDataStorage(S3Boto3Storage):
    location = common.AWS_LOCATION_TEST
    file_overwrite = False

    def __init__(self, *args, **kwargs):
        for k, v in kwargs.items():
            print("omg")
            print(v)

        super(UserDataStorage, self).__init__(*args, **kwargs)

How to pass the field user as an argument to the object UserDataStorage?

The problem here is, field user gets passed down to UserDataStorage but as a type <django.db.models.fields.related.ForeignKey>. I want a Profile instance here.

Is this achieveable in Django?

ishwor kafley
  • 938
  • 14
  • 32

1 Answers1

1

It's not possible the way you describe it. At this moment (when the code is initialized) the is no request/user objects to send.

What you can do is to pass a callable to the upload_to kwarg as explained in the docs.

This way when the callable is executed, you will have the model instance being saved, and this instance have the user attribute.

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)


class StorageModel(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="profile", null=False)
    file_meta = models.ImageField(
        upload_to=user_directory_path,
        storage=UserDataStorage(), 
        blank=False, null=False
    )
Todor
  • 15,307
  • 5
  • 55
  • 62