PenParse/penparse/webui/views/upload.py

57 lines
1.6 KiB
Python
Raw Normal View History

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
2024-12-10 12:04:26 +00:00
from django.db import transaction
from uuid import uuid4
from django.contrib.auth.decorators import login_required
2024-12-10 12:04:26 +00:00
from ..tasks import process_memo
logger = logging.getLogger(__name__)
@login_required
def upload_document(request: HttpRequest):
if request.method == "POST" and request.FILES.get("document"):
uploaded_file = request.FILES["document"]
# Check if the file is an image
if not uploaded_file.content_type.startswith("image/"):
messages.error(request, "Please upload an image file.")
return redirect("dashboard")
2024-12-10 12:04:26 +00:00
name, ext = os.path.splitext(uploaded_file.name)
new_name = f"{uuid4().hex}-{ext}"
# Save the image
file_name = default_storage.save(
f"uploads/{new_name}", ContentFile(uploaded_file.read())
)
# Create an ImageMemo instance
image_memo = ImageMemo(
image=file_name,
2024-12-10 12:04:26 +00:00
image_mimetype=uploaded_file.content_type,
content="", # You can add initial content here if needed
author=request.user, # Assuming the user is authenticated
)
2024-12-10 12:04:26 +00:00
transaction.on_commit(lambda: process_memo.delay(image_memo.id))
image_memo.save()
messages.success(request, "Image uploaded successfully!")
return redirect("dashboard") # Redirect to dashboard or appropriate page