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

时间:2012-05-03 14:25:58

标签: django

我有ImageField()我指定了upload_to路径。它可以保存到MEDIA_ROOT网址。但是我想将上传的文件更改为其他文件名。

我应该从forms.py还是从models.py那样做,还应该覆盖保存功能来存档吗?

forms.py

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

1 个答案:

答案 0 :(得分:3)

直接在ImageField头像的upload_to中进行自定义。

通常看起来像

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)

您可以在new_filename行引入新名称,取决于instancefilename或任何其他有意义的字符串。它甚至可以name the file by instance.pk