1👍
✅
Update Report model
image = models.ImageField(storage=PublicMediaStorage(), null=True, blank=True)
In views.py
from django.views.generic import View
class ReportImageDeleteView(View):
# you can either user POST, PUT or DELETE methods respectively
def get(self, request):
report = Report.objects.get(id=self.kwargs.get('pk'))
report.image = None
report.save()
return render(request, 'your_template.html')
# url
path(
'report/<int:pk>/delete/',
ReportImageDeleteView.as_view(),
name='image-delete'
),
in template
<input type="checkbox" onchange="clearImage({{ object.id }});" name="{{ object.image }}-clear">
<script>
function clearImage(id) {
var url = `/report/${id}/delete/`;
window.location = url; // redirect
}
</script>
0👍
try this
firstly edit your models.py like this so no one can upload any file except photos
class Report(models.Model):
image = models.ImageField(storage=PublicMediaStorage(), blank=True)
then in your views.py
from django.shortcuts import redirect
def delete_image(request, pk):
query = Report.objects.get(pk=id)
query.delete()
return redirect("/report/<int:pk>/")
then urls.py
path('delete_image/(?P<pk>\d+)/', views.delete_image, name='delete_image')
and in your html
<a href="{% url 'delete_image' image.id %}">Delete</a>
- [Answered ]-Django + Apache with mod_wsgi. Unable to load MySQLdb
- [Answered ]-Django 500 Error when DEBUG=FALSE, but only on some pages
- [Answered ]-Django – Userprofile field in my template
0👍
Write an APIView which does this:
views.py
class RemoveImageFromReportView(APIView):
"""Removes only the image uploaded from the Report instance."""
def delete(self, request, *args, **kwargs):
report = Report.objects.get(id=kwargs['pk'])
report.image.delete(save=True)
report.save()
return Response(data=None)
urls.py
urlpatterns = [
path(
"reports/<int:pk>/",
views.RemoveImageFromReportView.as_view(),
name="remove_image_from_instance",
),
]
On the html part. When the user clicks the delete image button make a ajax
request to this endpoint with the instance id. Note that the api request made must be a DELETE
method
If you want to delete the entire Report instance then use this link.
- [Answered ]-Regex: how to extract incomplete date and convert
- [Answered ]-JWT: How do I implement my custom error message on password or username is wrong Django REST
- [Answered ]-NOT NULL constraint failed: spring_post.publisher_id
- [Answered ]-Django model relations – "Owning" a related model enforced at the model level
Source:stackexchange.com