且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何更改上传文件的文件名?

更新时间:2022-10-15 11:54:42

ImageField 头像的rel =nofollow noreferrer> upload_to 。 / p>

通常看起来像

  def upload_to(instance,filename): 
import os.path
#从原始文件名获取扩展名
fn,ext = os.path.splitext(filename)
new_filename = ...
#返回新文件名,包括其父目录(基于MEDIA_ROOT)
返回path / {new_filename} {ext} .format(new_filename = new_filename,ext = ext)

您可以在 new_filename 行,取决于实例 filename 或任何其他字符串说得通。甚至可以将该文件命名为instance.pk


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)

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