我有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)
答案 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
行引入新名称,取决于instance
或filename
或任何其他有意义的字符串。它甚至可以name the file by instance.pk