Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete an ImageField image in a Django model

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 %}
like image 314
Nicholas Kajoh Avatar asked Dec 26 '16 10:12

Nicholas Kajoh


People also ask

How do I delete a specific record in Django?

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.

Which method deletes the specified file in Django?

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.


1 Answers

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

like image 97
kia Avatar answered Nov 12 '22 18:11

kia