PenParse/penparse/webui/views/delete.py

36 lines
1.1 KiB
Python
Raw Normal View History

from loguru import logger
from django.contrib import messages
from django.shortcuts import redirect
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from ..models import ImageMemo
from django.http import HttpRequest, HttpResponse
from django.contrib.auth.decorators import login_required
@login_required
def delete_document(request: HttpRequest, pk: str):
# find document with given ID (pk path param) and current user id
document = ImageMemo.objects.filter(id=pk, author__id=request.user.id).first()
if not document:
logger.debug(f"No memo found for user={request.user.id} and memo_id={pk}")
return HttpResponse(content="Document not found", status=404)
# delete file from storage
if default_storage.exists(document.image.name):
default_storage.delete(document.image.name)
else:
logger.warning(
"File {document.image.name} associated with doc {document.id} did not exist when we tried to delete it"
)
# delete document from database
document.delete()
return redirect("dashboard")