How to delete image from folder when deleting a record in django

How to delete/ remove image from folder when deleting a record in django.

In the index.html, we need to add the url along with the id in the delete button as shown below:

<td>
<a href="{% url 'delete-prod' p.id %}" class="btn btn-danger badge">Delete</a>
</td>

In the urls.py file, add the below path :

    path('delete-product/<str:pk>'views.deleteProductname="delete-prod")

In the views.py file, create a function and add the below code : 

def deleteProduct(requestpk):
    prod = Item.objects.get(id=pk)
    if len(prod.image) > 0:
        os.remove(prod.image.path)
    prod.delete()
    messages.success(request,"Product Deleted Successfuly")
    return redirect('/')

Watch the video given above for details explaination and video demo. 

© Copyright - 2018 - 2021 | All rights reserved at Funda of Web IT