diff --git a/akarpov/files/migrations/0012_alter_file_options_alter_file_file.py b/akarpov/files/migrations/0012_alter_file_options_alter_file_file.py new file mode 100644 index 0000000..d3f7ce2 --- /dev/null +++ b/akarpov/files/migrations/0012_alter_file_options_alter_file_file.py @@ -0,0 +1,25 @@ +# Generated by Django 4.2 on 2023-04-08 08:12 + +import akarpov.files.services.files +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("files", "0011_file_file_type_alter_file_description_and_more"), + ] + + operations = [ + migrations.AlterModelOptions( + name="file", + options={"ordering": ["modified"]}, + ), + migrations.AlterField( + model_name="file", + name="file", + field=models.FileField( + upload_to=akarpov.files.services.files.user_unique_file_upload + ), + ), + ] diff --git a/akarpov/files/models.py b/akarpov/files/models.py index 376659e..28cf9b1 100644 --- a/akarpov/files/models.py +++ b/akarpov/files/models.py @@ -10,8 +10,8 @@ from django.urls import reverse from model_utils.models import TimeStampedModel +from akarpov.files.services.files import user_unique_file_upload from akarpov.tools.shortener.models import ShortLink -from akarpov.utils.files import user_file_upload_mixin class File(TimeStampedModel, ShortLink): @@ -25,7 +25,7 @@ class File(TimeStampedModel, ShortLink): ) preview = FileField(blank=True, upload_to="file/previews/") - file = FileField(blank=False, upload_to=user_file_upload_mixin) + file = FileField(blank=False, upload_to=user_unique_file_upload) # meta name = CharField(max_length=100, null=True, blank=True) diff --git a/akarpov/files/services/files.py b/akarpov/files/services/files.py new file mode 100644 index 0000000..cfdd9f9 --- /dev/null +++ b/akarpov/files/services/files.py @@ -0,0 +1,16 @@ +import os + +from django.conf import settings + +from akarpov.utils.generators import generate_charset + + +def user_unique_file_upload(instance, filename): + """stores user uploaded files at their folder with unique file name""" + username = instance.user.username + path = os.path.join(settings.MEDIA_ROOT, f"files/{username}/") + slug = generate_charset(5) + while os.path.isdir(path + slug): + slug = generate_charset(5) + + return os.path.join(f"files/{username}/{slug}", filename)