如何在Django模型中删除ImageField图像 [英] How to delete an ImageField image in a Django model
本文介绍了如何在Django模型中删除ImageField图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Profile
模型,如下所示:
I have a Profile
model like so:
class Profile(models.Model):
photo = models.ImageField(upload_to="img/users/", blank=True)
我希望我的用户能够删除其个人资料照片,以使照片
中没有图像,即空白.
I want my users to be able to remove their profile pictures so that there's no image in photo
i.e blank.
我尝试了 Profile.objects.get(id = 1).photo.delete(save = False)
,该操作删除了图像,但URL仍然存在,所以我得到了404.我清除图片和网址了吗?
I tried Profile.objects.get(id=1).photo.delete(save=False)
which deleted the image but the url was still there so I was getting a 404. How do I clear the image and url?
编辑:在我的模板中,我喜欢:
In my template, I'm like:
{% if profile.photo %}
<img src="{{ MEDIA_URL }}{{ profile.photo }}" />
{% else %}
<img src="{{ MEDIA_URL }}img/avatar.jpg" />
{% endif %}
推荐答案
将 Profile.objects.get(id = 1).photo.delete(save = False)
更改为 Profile.objects.get(id = 1).photo.delete(save = True)
这篇关于如何在Django模型中删除ImageField图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文