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

Hir*_*uri 2 python django file django-views

我的文件夹中存储了一张图像media/logo/,我想FileField从我的视图中将其保存到我的模型中。这是我尝试过的方法,但遇到编码错误,并且在尝试保存文件后文件已损坏。

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


视图.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)
Run Code Online (Sandbox Code Playgroud)

我无法理解如何将文件保存到new_pathFileField 中,有什么想法吗?

Saj*_*ier 5

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

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

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

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()
Run Code Online (Sandbox Code Playgroud)

如果您想将内容复制到新文件,请使用@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
Run Code Online (Sandbox Code Playgroud)

在你的模型中

from app.storage import CustomFileStorage

fs = CustomFileStorage()

class Company(models.Model):
   logo = model.FileField(storage=fs)
Run Code Online (Sandbox Code Playgroud)