Django 重命名上传的文件:在末尾附加特定字符串

问题描述 投票:0回答:2
  • 我将上传按钮限制为仅允许 csv 文件。
  • 我需要帮助,请在用户上传的每个文件的末尾附加 _hello,但在扩展名之前。 (例如 user_file_name.csv 自动变为 user_file_name_hello.csv
  • 可选:我希望首先自动重命名原始文件,然后保存到我的上传目录。

模型.py

from django.db import models

# validation method to check if file is csv
from django.core.exceptions import ValidationError
def validate_file_extension(value):
    if not value.name.endswith('.csv'):
        raise ValidationError(u'Only CSV files allowed.')

# Create your models here.

class user_file(models.Model):
    user_file_csv = models.FileField(upload_to='documents/user_files/', validators=[validate_file_extension])

forms.py

from django import forms
from .models import user_file
from django.forms import FileInput

class user_file_form(forms.ModelForm):
    class Meta:
        model = user_file
        widgets = {'user_file_csv': FileInput(attrs={'accept': 'text/csv'})}
        fields = ('user_file_csv',)

谢谢!

django django-models filefield
2个回答
0
投票

也许你需要这样的东西:

class FileUploadUtil:

    @staticmethod
    def my_files_path(instance, filename):
        name, file_extention = os.path.splitext(filename)
        name = 'prefix-{}-{}-suffix.{}'.format(name, instance.id, file_extention)
        return "my_files/{}".format(name)


class MyModel(models.Model):
    # Other fields
    # ...
    my_file = models.FileField(max_length=300, upload_to=FileUploadUtil.my_files_path)

0
投票

可选:我希望首先自动重命名原始文件,然后保存到我的上传目录。

您可以重写 save() 方法。 检查这里 Django 文档

也许你需要装饰器。

from pathlib import Path


def rename_helper(path: str, append_text: str):
    stem, suffix = Path(path).stem, Path(path).suffix
    return f"{stem}{append_text}{suffix}"


def rename_previous_image(func):
    """ return wrapper object """
       
        
    def wrapper(*args, **kwargs):
        
        self = args[0]
        model = type(self)
        previous_obj = model.objects.filter(pk=self.pk)
        if previous_obj.exists():
            old_name_with_path = Path(str(previous_obj[0].user_file_csv))
            Path.rename(old_name_with_path , rename_helper(path=old_name_with_path , append_text="_hello"))
        return func(*args, **kwargs)

    return wrapper


并且,您可以装饰模型 save() 方法。


class MyModel(models.Model):
    # Other fields
    # ...
    my_file = models.FileField(max_length=300, upload_to=FileUploadUtil.my_files_path)

    @rename_previous_image
    def save(self, **kwargs):
        super(user_file, self).save(**kwargs)  # You must add This row.

此外,
建议重命名您的 user_file 类

像用户文件

检查此PEP 8

祝你有美好的一天。

© www.soinside.com 2019 - 2024. All rights reserved.