【问题标题】:How can I shorten the full path to the file, to the name of the file in djano admin forms?如何将文件的完整路径缩短为 djano 管理表单中的文件名?
【发布时间】:2021-06-11 22:20:45
【问题描述】:
我有一个标准的 Django 管理表单。
在文件选择框中上传文件时,我想只留下文件名,而不是静态中的完整路径。
这是否可以在不编辑模板的情况下实现,而只能通过覆盖表单集、表单或模型方法来实现?
在按钮上方的图片中,将“ws_document_studygroup/2021/2/123123123123123123png”行的显示更改为“123123123123123123png”。但不改变模型中的真实路径。
请告知最佳做法。
【问题讨论】:
标签:
python
django
django-forms
django-admin
【解决方案1】:
您可以尝试将@property getter 添加到您的模型类中:
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 函数采用路径并返回最后一个斜杠字符(即文件名)之后的路径段。
>>> doc = Document("ws_document_studygroup/2021/2/123123123123123123.png")
>>> doc.filename
123123123123123123.png
所以你需要做的就是在你的模板中使用这个属性。
【解决方案2】:
我找到了解决这个问题的不同方法。
我覆盖 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__'
并将表单添加到 Inline。
希望对某人有所帮助。