我已成功将文件上传到数据库(运行正常)。问题在于,如果媒体文件夹被删除,文件将存储在数据库中,这将引发错误[WinError 2] The system cannot find the file specified: ...
。因此,我的问题是如何处理此错误。
如果文件存在于数据库中但不存在于媒体文件夹中,则我希望处理此错误并显示模板而无需出错。我该怎么做?
模板
{% for document in documents %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{document.filename|truncatechars:15}}</td>
<td>{{document.file.size|filesizeformat}}</td>
<td>{{document.category}}</td>
<td>{{document.file.url}}</td>
<tr>
{% endfor %}
模型
class Document(models.Model):
category = models.ForeignKey(DocumentCategory, on_delete=models.CASCADE)
file = models.FileField(upload_to='media/',
validators=[FileExtensionValidator(['pdf', 'xlsx', 'pptx', 'docx','xls']), file_size])
created = models.DateTimeField(auto_now_add=True)
@property
def filename(self):
return os.path.basename(self.file.name)