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

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

问题描述

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": ["This field is required."]}, "success": false}

在 FileUpload.original_filename 中添加 blank=True, null=True 允许上传成功,但不保存原始文件名.在 Django 1.5 上.根据这篇文章,这应该可行.

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, this should work.

推荐答案

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

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天全站免登陆