2

我们需要将一些小文件存储到数据库中(是的,我很清楚反对意见,但是设置例如 FileField 以在多个环境中工作对于几个文件来说似乎非常乏味,并且在数据库中保存文件也会解决备份需求)。

然而,我惊讶地发现,即使 BinaryField 可以设置为可编辑,Django Admin 也不会为其创建文件上传小部件。

BinaryField 我们需要的唯一功能是可以上传文件并替换现有文件。除此之外,Django Admin 满足了我们所有的要求。

我们如何对 Django Admin 进行这种修改?

4

2 回答 2

1

您将需要Widget专门创建一个自定义项,BinaryField该自定义项必须在将文件内容放入数据库之前对其进行读取。

class BinaryFileInput(forms.ClearableFileInput):

    def is_initial(self, value):
        """
        Return whether value is considered to be initial value.
        """
        return bool(value)

    def format_value(self, value):
        """Format the size of the value in the db.

        We can't render it's name or url, but we'd like to give some information
        as to wether this file is not empty/corrupt.
        """
        if self.is_initial(value):
            return f'{len(value)} bytes'


    def value_from_datadict(self, data, files, name):
        """Return the file contents so they can be put in the db."""
        upload = super().value_from_datadict(data, files, name)
        if upload:
            return upload.read()

然后您需要通过以下方式在管理员中使用它:

class MyModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.BinaryField: {'widget': BinaryFileInput()},
    }

    fields = ('name', 'your_binary_file')

笔记:

  • BinaryField没有 url 或文件名,因此您将无法检查数据库中的内容
  • 上传文件后,您将能够看到存储在数据库中的值的字节大小
  • 您可能希望扩展小部件以便能够通过读取文件的内容来下载文件
于 2019-11-03T22:23:20.727 回答
-1

@Ania Warzecha,对不起,但是如何扩展它以供下载?

于 2019-11-13T15:00:25.123 回答