如何将文件的完整路径缩短为 djano 管理表单中的文件名?

How can I shorten the full path to the file, to the name of the file in djano admin forms?

我有一个标准的 Django 管理表单。 在文件选择框上传文件时,我想只留下文件名,而不是静态的完整路径。 这是否可以在不编辑模板的情况下实现,而只能通过覆盖表单集、表单或模型方法来实现?

在按钮上方的图片中,将“ws_document_studygroup/2021/2/123123123123123123png”行的显示更改为“123123123123123123png”。但是没有改变模型中的真实路径。 请告知最佳做法。

您可以尝试将 @property getter 添加到您的模型中 class:

import os


class Document:

    def __init__(self, full_path: str):
        self.full_path = full_path

    @property
    def filename(self) -> str:
        return os.path.basename(self.full_path)

os.path.basename 函数接受一个路径和 returns 最后一个斜杠字符(换句话说,文件名)后面的路径段。

>>> doc = Document("ws_document_studygroup/2021/2/123123123123123123.png")
>>> doc.filename
123123123123123123.png

所以您需要做的就是在您的模板中使用这个 属性。

我找到了解决此问题的不同方法。

我覆盖了 ClearableFileInput 小部件和 clearable_file_input.html 模板

from django.forms import ClearableFileInput
import os


class CustomClearableFileInput(ClearableFileInput):
    template_name = 'custom_clearable_file_input.html'

    def format_value(self, value):
         """
         Return the file object if it has a defined url attribute.
         """
         if self.is_initial(value):
              setattr(value, 'file_short_name', os.path.basename(str(value)))
              return value

并在模板文件中将字符串更改为:

<a href="{{ widget.value.url }}">{{ widget.value.file_short_name }}</a>

只需将小部件添加到文件字段:

class StudyGroupDocumentsForm(forms.ModelForm):
file = forms.FileField(widget=CustomClearableFileInput)

class Meta:
    model = StudyGroupDocuments
    fields = '__all__'

并将表单添加到内联。

希望对大家有所帮助。