Django根据id删除图像

时间:2015-08-11 11:23:53

标签: python django django-models django-orm

假设我有以下简单模型:

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信号,但是如何删除图像呢?

2 个答案:

答案 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是文件路径