如何更改上传文件的文件名? [英] How to change the filename on uploaded file?

查看:158
本文介绍了如何更改上传文件的文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我应该从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)


解决方案

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

这篇关于如何更改上传文件的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆