How To Delete An Image Using Django?
I want to know how to add a delete button in my form for deleting an image. The project is a simple 'Pics viewer', the index shows all the images that are stored but I want to add
Solution 1:
urls.py
[.........]
url(
r'^delete-image/(?P<id>\d+)/$',
'delete_image',
name="delete_image"
),
[.........]
views.py
def delete_image(request, id):
image = Image.objects.get(pk=id).delete()
return HttpResponseRedirect(reverse('app_name:url_name'))
template
<ul>
{% for image in images_list %}
<li>
<img src="/{{ image.image }}" height="75" />
<a href="{% url app_name:delete_image image.id %}">Delete</a>
</li>
{% endfor %}
</ul>
Solution 2:
views.py
from django.views.generic.edit import DeleteView
from django.core.urlresolvers import reverse_lazy
from myapp.models import Image
class ImageDelete(DeleteView):
model = Image
success_url = reverse_lazy('index')
urls.py
from myapp.views import index, ImageDelete
...
url(r'^image/(?P<id>\d+)/delete/$', ImageDelete.as_view(), name="image-delete"),
...
index.html
{% for image in images_list %}
<li>
<img src="/{{ image.image }}" height="75" />
<a href="{% url 'myapp:image-delete' image.id %}">Delete</a>
</li>
{% endfor %}
Post a Comment for "How To Delete An Image Using Django?"