假设我有以下简单模型:
class GraphData(models.Model):
"""
Stores graph data for easy access
"""
uid = models.CharField(max_length=10, db_column='uid')
graph_params = models.TextField(db_column='graph_params')
当删除数据库中的行时,我想删除位于server.com/images/<uid>.png
的图像。
我知道我需要捕获pre_delete
信号,但是如何删除图像呢?
答案 0 :(得分:2)
首先,配置您的MEDIA_ROOT
:
import os
# Project root is intended to be used when building paths,
# e.g. ``os.path.join(PROJECT_ROOT, 'relative/path')``.
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
# Absolute path to the directory that will hold uploaded files.
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'uploads/')
然后您可以使用os.remove()
:
import os
from django.conf import settings
def delete_file(path):
"""
Deletes specified file from uploads.
Usage:
delete_file('path/to/file.extension')
"""
os.remove(os.path.join(settings.MEDIA_ROOT, path))
答案 1 :(得分:0)
一种非常简单的方法是使用我们在python中使用的os.remove。
例如:os.remove(path)
其中path是文件路径