问题
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