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 %}
To delete a record we do not need a new template, but we need to make some changes to the members template. Of course, you can chose how you want to add a delete button, but in this example, we will add a "delete" link for each record in a new table column. The "delete" link will also contain the ID of each record.
Use os.remove() function to delete File The OS module in Python provides methods to interact with the Operating System in Python. The remove () method in this module is used to remove/delete a file path.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With