From 600d85d7d611c2e558970b6d7fad0a9218e697f5 Mon Sep 17 00:00:00 2001 From: Aroy-Art Date: Thu, 22 Feb 2024 12:31:18 +0100 Subject: [PATCH] Check for if file in form & validity --- archivist/apps/files/views.py | 49 +++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/archivist/apps/files/views.py b/archivist/apps/files/views.py index 3a96eba..fdaefb0 100644 --- a/archivist/apps/files/views.py +++ b/archivist/apps/files/views.py @@ -70,27 +70,36 @@ def fileUpload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): - file = form.cleaned_data['file'] - - file_name = file.name - file_hash = compute_file_hash(file) - - Null, file_ext = os.path.splitext(file_name) - hash_file_name = file_hash + file_ext - - new_submission_file, created = Submission_File.objects.get_or_create(file_hash=file_hash) - - new_submission_file.file_hash = file_hash - new_submission_file.file_name = file_name - new_submission_file.file.save(hash_file_name, file) - - new_submission_file.save - - return HttpResponseRedirect(f"/files/submission/{file_hash}") - + if 'file' in request.FILES: # Check if a file has been uploaded + file = form.cleaned_data['file'] + + file_name = file.name + file_hash = compute_file_hash(file) + + Null, file_ext = os.path.splitext(file_name) + hash_file_name = file_hash + file_ext + + new_submission_file, created = Submission_File.objects.get_or_create(file_hash=file_hash) + + new_submission_file.file_hash = file_hash + new_submission_file.file_name = file_name + new_submission_file.file.save(hash_file_name, file) + + new_submission_file.save + + return HttpResponseRedirect(f"/files/submission/{file_hash}") + + else: + # No file was uploaded, add an error message to the context + error_message = 'No file was uploaded.' + return render(request, 'files/upload.html', {'form': form, 'error_message': error_message}) + + else: + # Form is not valid, add an error message to the context + error_message = 'There was an error with the form.' + return render(request, 'files/upload.html', {'form': form, 'error_message': error_message}) + else: form = UploadFileForm() return render(request, 'files/upload.html', {'form': form}) - -