S
S
sazhyk2016-08-11 11:26:17
Django
sazhyk, 2016-08-11 11:26:17

How to store user files in Django?

Please share your thoughts or experience in implementing file storage for different users. The task is this: it is necessary that users in their personal accounts be able to upload files through the form, and that these files are available only to their creators.
Something like this: the user user1uploads his files to /storage/path/to/user1/date/time/file.name, and in his personal account he has a link to this file. Also, the user can delete this file, and it should be deleted from the repository too.
Suddenly someone implemented something similar, or there are ready-made modules for django. I just can't figure out what query to ask this on Google.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2016-08-11
@sazhyk

Create a model (let's call it UserFiles) with fields file and a key for the user model.
Take request.user.userfiles_set.all() in the view or filter as you need.
For more complex implementations read more documentation.

I
Ilya Chichak, 2016-08-18
@ilya_chch

in settings.py add an indication of the location of the media

MEDIA_URL = '/media/' #например
MEDIA_ROOT = '/srv/files/media' #например

media_url - part of the url where the images will be located, media_root - the place on the server where nginx will look for them.
in model:
class ModelClass(models.Model):
    <поле> = models.ImageField(upload_to=rename_image, blank=True, verbose_name='...')

def rename_image(instance, filename):
    image_name = md5(str(time.time()).encode()).hexdigest()
    image_type = filename.split('.')[-1]
    return 'imgs/{}.{}'.format(image_name, image_type)

rename_image in my case renames the uploaded image to a hash. and you can add a path to return. in my case will load into media_root/imgs/<something>.jpg #for example (assuming media_root is defined, everything will always fall there)
add a subdirectory called user_{its id} to the path. and here about availability only for this user - it is necessary to think separately.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question