Search code examples
pythondjangofile-rename

Rename a file on upload Django


Good afternoon, I need to rename the files that users upload through a form with the nomenclature (DSR_"rut"-"name"-"label name (from form)"-0-"extension"). The parts of the rut, the name and the extension I could already generate, but I don't know how to do the name of the label. example: if the label says "image": (DSR_"rut"-"name"-image-0-"extension").

Please your help.

To do this use the following:

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)

The file forms is as follows:

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'}),
            
        }

Solution

  • As you can see in the docs the function passed to upload_to expects only two arguments. So, it is not possible to do with one function, you have to work arround it:

    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)
    

    Also, there is a problem with your form, namely ValueError: ClearableFileInput doesn't support uploading multiple files.. So, remove "multiple":True from widget attrs.