您将需要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 或文件名,因此您将无法检查数据库中的内容
- 上传文件后,您将能够看到存储在数据库中的值的字节大小
- 您可能希望扩展小部件以便能够通过读取文件的内容来下载文件