我有一个看起来像这样的django模型
class Foo(models.Model):
...
article = models.FileField(upload_to='articles', blank=True, default=None, null=True)
...
当我尝试使用bar
删除Foo模型的对象bar.delete()
时,文章字段中没有上传任何文件,我收到以下错误。
[Error2] Is a directory
如何删除此类对象?
修改
删除代码如下所示:
HTML
<div class="form-group">
<input type="radio" name="delete" value="yes" /> Delete
<input type="radio" name="delete" value="no" checked="checked" /> Don't Delete
</div>
DJANGO
def del_foo(request,foo_id):
context_dict = {'msg':'Unable to delete'}
try:
bar = models.Foo.objects.get(id=foo_id)
_delete = True if request.POST.get("delete")=="yes" else False
if _delete:
bar.delete()
return HttpResponseRedirect('/home')
except Exception as e: print str(e)
return render(request, 'edit.html', context_dict)
答案 0 :(得分:1)
您没有包含删除操作的相关代码,但听起来像是在调用os.remove(path)
。由于文件名为空,因此要删除的路径构造为os.path.join(dir, '')
,只会产生 dir 。调用os.remove(dir)
会导致您指出的错误。您需要在删除操作中避免这种情况。
def delete(self):
if self.article:
# delete operation
# rest of delete, maybe the default parent delete
super(Foo, self).delete(*args, **kwargs)
当然,你可以做更复杂的事情,但这应该指向你一个有希望的方向。
答案 1 :(得分:-1)
在Django 1.9中 我创建了
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Foo(models.Model):
article = models.FileField(upload_to='articles', blank=True, default=None, null=True)
然后我创建了两个对象
Foo.objects.create(pk=1)
Foo.objects.create(pk=2)
然后我试图删除它
Foo.objects.get(pk=1).delete()
(1, {u'Foo': 1})
它的功效就像魅力一样!