重命名上传的文件Django

xdnvmnnf  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(114)

下午好,我需要重命名用户通过表单上传的文件,命名方式为(DSR_“rut”-“name”-“label name(from form)"-0-“extension”)。我已经可以生成车辙的部分、名称和扩展名,但我不知道如何生成标签的名称。例如:如果标签上写着“图像”:(DSR_“rut”-“name”-image-0-“extension”)。
请你帮忙。
要执行此操作,请使用以下命令:

def upload_directory_name(instance, filename):
    ext = filename.split('.')[-1]
    filename = "DSR_%s_%s_0.%s" % (instance.rut, instance.name, ext)
    return os.path.join('uploads',filename)

文件格式如下:

class Candidato_form2(forms.ModelForm):

    class Meta:
        model = Candidato

        fields = [
            
            'certificado_antecedentes',
            'hoja_de_vida_conductor',
            

        ]

        labels = {
            
            'certificado_antecedentes': 'Certificado Antecedentes',
            'hoja_de_vida_conductor': 'Hoja de vida del conductor',
        
        }

        widgets = {
            
            'certificado_antecedentes': forms.ClearableFileInput(attrs={"multiple":True, 'class':'form-control'}),
            'hoja_de_vida_conductor': forms.ClearableFileInput(attrs={"multiple":True, 'class':'form-control'}),
            
        }
brc7rcf0

brc7rcf01#

docs中可以看到,传递给upload_to的函数只需要两个参数。所以,它是不可能做一个功能,你必须围绕它工作:

def create_path(instance, filename, file_type):
    ext = filename.split('.')[-1]
    new_filename = "DSR_%s-%s-%s-0.%s" % (instance.rut, instance.name, file_type, ext)
    return os.path.join('uploads',new_filename)

def cert_upload_path(instance, filename):
    return create_path(instance, filename, 'cert')

def hoja_upload_path(instance, filename):
    return create_path(instance, filename, 'hoja')

class Candidato(models.Model):
    ...
    certificado_antecedentes = models.FileField(upload_to=cert_upload_path)
    hoja_de_vida_conductor = models.FileField(upload_to=hoja_upload_path)

另外,您的表单有一个问题,即ValueError: ClearableFileInput doesn't support uploading multiple files.。因此,从widget attrs中删除"multiple":True

相关问题