使用FileField在Django中保存原始文件名 [英] Saving Original File Name in Django with FileField

查看:548
本文介绍了使用FileField在Django中保存原始文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ {code> def generate_uuid_file_name(self,filename):
self.original_filename = filename
extension = filename.rsplit('。',1)[1]
newfilename = uuid.uuid4().__ str __()+'。'+ extension
return self.directory()+ newfilename

class FileUpload(models.Model):
original_filename = models.CharField(max_length = 128)
fileobj = models.FileField(upload_to = generate_uuid_file_name)

在上传时,

  {errors:{original_filename:[此字段为必填项。 },success:false} 

添加blank = True,null = True FileUpload.original_filename允许上传成功,但不保存原始文件名。在django 1.5。根据这篇文章: Django:如何在FileField中保存原始文件名?这应该工作。任何帮助非常感谢。

解决方案

在视图中执行(null = True,blank = True再次成为模型的一部分):

  file_object = UploadFileForm.save(commit = False)
file_object.original_filename = request.FILES ['file']。name
file_object.save()

请注意,您需要根据您的上下文等


def generate_uuid_file_name(self, filename):
    self.original_filename = filename
    extension = filename.rsplit('.', 1)[1]
    newfilename = uuid.uuid4().__str__() + '.' + extension
    return self.directory() + newfilename

class FileUpload(models.Model):
    original_filename  = models.CharField(max_length=128)
    fileobj            = models.FileField(upload_to=generate_uuid_file_name)

On upload,

{"errors": {"original_filename": ["This field is required."]}, "success": false}

Adding blank=True, null=True to the FileUpload.original_filename allows the upload to succeed but does not save the original file name. On django 1.5. According to this post: Django: How to save original filename in FileField? This should work. Any help much appreciated.

解决方案

Do that in the view (after null=True, blank=True are again part of your model):

file_object = UploadFileForm.save(commit=False)
file_object.original_filename = request.FILES['file'].name
file_object.save()

Mind that you will need to change the above code accordingly with your context etc

这篇关于使用FileField在Django中保存原始文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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