关于django1.3的admin里删除model同时删除文件的问题[转]
作者:我就是个世界
发表于:2011-10-01
我的一个Model里有个FileField字段,用来存储文件路径,但是发现1.3版在django admin里面删除model的时候,存储在硬盘上的文件没有一起删除
我查找官方文档,似乎这个功能是在1.3版后改变了(似乎这个活儿django不管了,覆写的delete()方法不会被调用了)。
[b]我的代码:[/b][separator]
[code]
class BossGT8(models.Model):
name = models.CharField(max_length=30)
artist = models.CharField(max_length=40)
created = models.DateTimeField(auto_now_add=True)
uploader = models.CharField(max_length=30)
download = models.IntegerField(default=0)
filename = models.FileField(upload_to='patch_files/boss_gt8')
filesize = models.IntegerField(default=0)
description = models.TextField(max_length=800, blank=True, verbose_name='Description')
rating = models.IntegerField(default=0)
isshow = models.BooleanField(default=True)
[/code]
[b]解决方法是:[/b]
[color=#FF0000]用了 django.db.models.signals的post_delete方法[/color]
代码如下:
[code]
#in models.py
from django.db import models
from django.db.models.signals import post_delete
import os
class BossGT8(models.Model):
name = models.CharField(max_length=30)
created = models.DateTimeField(auto_now_add=True))
filename = models.FileField(upload_to='patch_files')
def delete_file(sender, **kwargs):
patch = kwargs['instance']
os.remove(patch.filename.path)
post_delete.connect(delete_file, sender=BossGT8)
[/code]
来源:http://www.douban.com/group/topic/22652613/
我查找官方文档,似乎这个功能是在1.3版后改变了(似乎这个活儿django不管了,覆写的delete()方法不会被调用了)。
[b]我的代码:[/b][separator]
[code]
class BossGT8(models.Model):
name = models.CharField(max_length=30)
artist = models.CharField(max_length=40)
created = models.DateTimeField(auto_now_add=True)
uploader = models.CharField(max_length=30)
download = models.IntegerField(default=0)
filename = models.FileField(upload_to='patch_files/boss_gt8')
filesize = models.IntegerField(default=0)
description = models.TextField(max_length=800, blank=True, verbose_name='Description')
rating = models.IntegerField(default=0)
isshow = models.BooleanField(default=True)
[/code]
[b]解决方法是:[/b]
[color=#FF0000]用了 django.db.models.signals的post_delete方法[/color]
代码如下:
[code]
#in models.py
from django.db import models
from django.db.models.signals import post_delete
import os
class BossGT8(models.Model):
name = models.CharField(max_length=30)
created = models.DateTimeField(auto_now_add=True))
filename = models.FileField(upload_to='patch_files')
def delete_file(sender, **kwargs):
patch = kwargs['instance']
os.remove(patch.filename.path)
post_delete.connect(delete_file, sender=BossGT8)
[/code]
来源:http://www.douban.com/group/topic/22652613/
请发表您的评论