How to delete an ImageField image in a Django model

十年热恋 提交于 2021-01-22 05:45:56

问题


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.

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?

EDIT: In my template, I'm like:

{% if profile.photo %}
    <img src="{{ MEDIA_URL }}{{ profile.photo }}" />
{% else %}
    <img src="{{ MEDIA_URL }}img/avatar.jpg" />
{% endif %}

回答1:


Change Profile.objects.get(id=1).photo.delete(save=False) to Profile.objects.get(id=1).photo.delete(save=True)

https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.fields.files.FieldFile.delete



来源:https://stackoverflow.com/questions/41329858/how-to-delete-an-imagefield-image-in-a-django-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!