move to django default storage for uploads

This commit is contained in:
James Ravenscroft 2024-12-09 10:06:41 +00:00
parent a27298cff0
commit 7176e8ce09
4 changed files with 48 additions and 8 deletions

View File

@ -30,6 +30,12 @@
class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 transition duration-300"
>Download</a
>
<form action="{% url 'delete_document' document.id %}" method="post" onsubmit="return confirm('Are you sure you want to delete this document?');">
{% csrf_token %}
<button type="submit" class="bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600 transition duration-300">
Delete
</button>
</form>
</div>
</div>
{% empty %}

View File

@ -145,4 +145,6 @@ def test_document_thumbnail_file_missing(client, cleanup_uploaded_files, caplog)
assert response.status_code == 404
assert response.content == b"Document not found"
assert "The file associated with this document does not exist" in caplog.text
assert (
f"The file associated with memo {image_memo.id} does not exist" in caplog.text
)

View File

@ -0,0 +1,31 @@
import logging
import os
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
logger = logging.getLogger(__name__)
@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
default_storage.delete(document.image.name)
return redirect("dashboard")

View File

@ -33,13 +33,12 @@ def document_thumbnail(request: HttpRequest, pk: str):
thumb_path = os.path.join(thumbnail_dir, str(document.id) + ".jpg")
if not os.path.exists(thumb_path):
if not default_storage.exists(thumb_path):
if not os.path.exists(thumbnail_dir):
os.makedirs(thumbnail_dir)
if not os.path.exists(document.image.name):
logger.warning("The file associated with this document does not exist")
if not default_storage.exists(document.image.name):
logger.warning(
f"The file associated with memo {document.id} does not exist"
)
return HttpResponse(content="Document not found", status=404)
# Open the image using PIL
@ -64,9 +63,11 @@ def document_thumbnail(request: HttpRequest, pk: str):
# Save the thumbnail to a BytesIO object
thumb_io = BytesIO()
image.save(thumb_path, format="JPEG")
image.save(thumb_io, format="JPEG")
thumb_io.seek(0)
default_storage.save(thumb_path, thumb_io)
# Return the thumbnail as an HTTP response
with open(thumb_path, "rb") as f:
return HttpResponse(f.read(), content_type="image/jpeg")