Reputation: 1677
I'm developing a file manager with Django. I'm using SFTP file server and django-storage package for managing files.
Well I developed some Apis for users to create and modify directories under their-own root-directory (which is abstract to the users) so far. Now I want to able users to upload their files onto their sub-directories or move files between those sub-directories but I don't know how?!
This is the model I'm using for file management:
def user_directory_path(instance, filename):
return 'user_{0}/{1}'.format(format(instance.owner.id, '010d'), filename)
class UploadedFile(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=150)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
file = models.FileField(upload_to=user_directory_path)
As you can see, currently files will be uploaded to <server-root>/user_<10digit-userid>/
directory.
Thanks in advance.
Upvotes: 1
Views: 342
Reputation: 1677
In the last I added an extra CharField
to my model named upload_to
and I used it in user_directory_path
function to indicate sub-directory of the file.
def user_directory_path(instance, filename):
if instance.upload_to != '' and instance.upload_to[-1] != '/':
upload_to = instance.upload_to + '/'
else:
upload_to = instance.upload_to
return 'user_{0}/{1}{2}'.format(format(instance.owner.id, '010d'), upload_to, filename)
class UploadedFile(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=150)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
file = models.FileField(upload_to=user_directory_path)
upload_to = models.CharField(max_length=255, default='')
Upvotes: 1