如何从其路径将图像保存到FileField?

时间:2017-12-09 15:01:05

标签: python django file django-views

我的media/logo/文件夹中存有图片,我想将其保存到我的模型FileField中。这是我尝试过但我得到的编码错误&在我尝试保存文件后,文件已损坏。

  

UnicodeDecodeError:'charmap'编解码器无法解码字节...

views.py:

def save_records(request):
    new_path = os.path.join(settings.MEDIA_ROOT, 'logo', filename)
    same_file = File(new_path, filename)
    Company.objects.create(logo=same_file)

我在理解如何将new_path中的文件保存到FileField时遇到了一些麻烦?

2 个答案:

答案 0 :(得分:2)

如果您希望FileField使用现有文件而不是创建新文件。

def save_records(request):
    c = Company()
    c.logo.name = 'logo/<filename>'  #relative to the media root.
    c.save()

并且,如果要修改现有记录的文件名

old_path = c.logo.path
c.logo.name = 'logo/<new filename>'  #relative to the media root.
new_path = settings.MEDIA_ROOT + c.logo.name
os.rename(old_path, new_path)
c.save()

如果要将内容复制到新文件,请使用@Roman Miroshnychenko的解决方案。

Django的FileField在内部使用FileSystemStorage来存储和编辑文件,因此您可以覆盖其行为。这将确保Django始终使用提供的文件名,而不是生成新文件名。

from django.core.files.storage import FileSystemStorage

class CustomFileStorage(FileSystemStorage):

    def get_available_name(self, name):
        return name # returns the same name

在你的模特中

from app.storage import CustomFileStorage

fs = CustomFileStorage()

class Company(models.Model):
   logo = model.FileField(storage=fs)

答案 1 :(得分:0)

根据the docs File类,期望文件对象作为第一个参数,而不是路径字符串。你需要这样做:

with open(new_path, 'rb') as fo:
    same_file = File(fo, filename)
    Company.objects.create(logo=same_file)
相关问题