将BinaryField的文件上传小部件添加到Django Admin [英] Adding file upload widget for BinaryField to Django Admin

查看:122
本文介绍了将BinaryField的文件上传小部件添加到Django Admin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要将一些较小的文件存储到数据库中(是的,我很清楚这些反对意见,但是将FileField设置为在几种环境中工作对于两个文件来说似乎很繁琐,并且将文件放在数据库也会解决备份要求。)

We need to store a few smallish files to the database (yes, I'm well aware of the counterarguments, but setting up e.g. FileField to work in several environments seems very tedious for a couple of files, and having files on the database will also solve backup requirements).

但是,令我惊讶的是,即使BinaryField可以设置为可编辑,但Django Admin并未为该文件创建文件上传小部件

However, I was surprised to find out that even though BinaryField can be set editable, Django Admin does not create a file upload widget for it.

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

The only functionality we need for the BinaryField is the possibility to upload a file and replace the existing file. Other than that, the Django Admin fulfills all our requirements.

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

How can we do this modification to Django Admin?

推荐答案

您将要创建专门用于 BinaryField 的自定义 Widget 在将文件内容放入数据库之前,必须先读取文件内容。

You will want to create a custom Widget specifically for BinaryField which has to read the file contents before putting them into the database.

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()

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

And then you need to use it in admin in the following way:

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

    fields = ('name', 'your_binary_file')

注意:


  • BinaryField 没有网址或文件名,因此您将无法检查数据库中的内容

  • 上传文件后,您将能够仅查看存储在db中的值的字节大小

  • 您可能希望扩展小部件,以便能够通过读取文件
    的内容来下载文件
  • BinaryField doesn't have a url or a file name so you will not be able to check what's in the db
  • After uploading the file you will be able to see just the byte size of the value stored in the db
  • You might want to extend the widget to be able to download the file by reading it's contents

这篇关于将BinaryField的文件上传小部件添加到Django Admin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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