How to change the filename on uploaded file?

2020-08-01 07:01发布

问题:

I have a ImageField() where I have specified the upload_to path. And it works it saves to the MEDIA_ROOT url. However I want to change the uploaded file to some other filename.

Should I do that from the forms.py or from the models.py, and also should I override the the save function to archive that?

forms.py

class UserAvatarForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('avatar',)
    def __init__(self, *args, **kwargs):
        super(UserAvatarForm, self).__init__(*args, **kwargs)

回答1:

Customize it in upload_to of the ImageField avatar directly.

Normally it looks like

def upload_to(instance, filename):
    import os.path
    # get extension from raw filename
    fn, ext = os.path.splitext(filename)
    new_filename = ...
    # return new filename, including its parent directories (based on MEDIA_ROOT)
    return "path/{new_filename}{ext}".format(new_filename=new_filename, ext=ext)

You could introduce new name at the new_filename line, depends on instance or filename or any other strings that makes sense. It's even possible to name the file by instance.pk



标签: django