attachment_remove.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. from django.contrib import messages
  2. from django.contrib.auth.decorators import login_required
  3. from django.core.exceptions import PermissionDenied
  4. from django.shortcuts import get_object_or_404, redirect
  5. from django.urls import reverse
  6. from tickets.models import Attachment
  7. from tickets.utils import remove_attachment_file
  8. @login_required
  9. def remove_attachment(request, attachment_id):
  10. if request.method == "POST":
  11. attachment = get_object_or_404(Attachment, pk=attachment_id)
  12. # Permissions
  13. is_admin_or_staff = request.user.is_superuser or request.user.is_staff
  14. is_attachment_accessible = (
  15. attachment.added_by == request.user or
  16. attachment.ticket.created_by == request.user and (
  17. attachment.ticket.assigned_to == request.user or
  18. attachment.ticket.list.group in request.user.groups.all()
  19. )
  20. )
  21. if not (is_admin_or_staff or is_attachment_accessible):
  22. raise PermissionDenied
  23. if remove_attachment_file(attachment.id):
  24. messages.success(request, f"The attachment has been successfully deleted.")
  25. else:
  26. messages.error(request, f"Sorry, there was a problem deleting attachment.")
  27. return redirect(reverse("tickets:ticket_detail", kwargs={"pk": attachment.ticket.pk}))
  28. else:
  29. raise PermissionDenied