删除图片&带有sorl.thumbnail的缩略图(Django)

时间:2016-10-29 15:45:18

标签: python django

我正在使用Python 2.7,Django 1.9和sorl.thumbnail。

我无法创建一个视图来删除原始图片文件,数据库中的Picture条目,sorl.thulbnail生成的缩略图以及数据库中的thumbnail_kvstore条目。

这是我的图片模型:

class Picture(models.Model):
    file = models.ImageField(upload_to="pictures")
    slug = models.SlugField(max_length=100, blank=True)
    user = models.ForeignKey(User, null=True, blank=True)
    exiflnglat = models.PointField(dim=3, geography=True, blank=True, null=True)
    objects = models.GeoManager()

    def __str__(self):
        return self.slug

    @models.permalink
    def get_absolute_url(self):
        return ('upload-new', )

以下是我的观点:

from sorl.thumbnail import delete

def deletepicnthumbs(request, pk):
    allpicfromuser = Picture.objects.filter(user=request.user)
    pictodelete = allpicfromuser.get(id=pk)
    delete(pictodelete)
    return redirect(adddetails)

此视图不会删除任何内容..我做错了什么?

非常感谢

1 个答案:

答案 0 :(得分:1)

您似乎正在尝试使用sorl中的delete方法删除Picture模型的实例,而不是图片本身。

此代码应该有效:

from sorl.thumbnail import delete

def deletepicnthumbs(request, pk):
    pictodelete = Picture.objects.get_object_or_404(id=pk, user=request.user)
    # Delete the thumbnails, as well as the original image
    # If you want to keep the original image, pass ```delete_file=False```
    delete(pictodelete.file)
    # We use Django's method to delete the Picture instance, if needed
    pictodelete.delete()
    return redirect(adddetails)

希望这有帮助, 阿德拉