diff --git a/dmoj/urls.py b/dmoj/urls.py index a7dacb8..82d0925 100644 --- a/dmoj/urls.py +++ b/dmoj/urls.py @@ -60,6 +60,7 @@ from judge.views import ( resolver, course, email, + custom_file_upload, ) from judge import authentication @@ -1193,6 +1194,7 @@ urlpatterns = [ ), ), url(r"^resolver/(?P\w+)", resolver.Resolver.as_view(), name="resolver"), + url(r"^upload/$", custom_file_upload.file_upload, name="custom_file_upload"), ] + url_static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # if hasattr(settings, "INTERNAL_IPS"): diff --git a/judge/views/custom_file_upload.py b/judge/views/custom_file_upload.py new file mode 100644 index 0000000..cdc4f8e --- /dev/null +++ b/judge/views/custom_file_upload.py @@ -0,0 +1,43 @@ +from django.shortcuts import render +from django.core.files.storage import FileSystemStorage +from django import forms +from django.utils.translation import gettext as _ +from django.conf import settings +from django.http import Http404 + +import os +import secrets +from urllib.parse import urljoin + +MEDIA_PATH = "uploads" + + +class FileUploadForm(forms.Form): + file = forms.FileField() + + +def file_upload(request): + if not request.user.is_superuser: + raise Http404() + file_url = None + if request.method == "POST": + form = FileUploadForm(request.POST, request.FILES) + if form.is_valid(): + file = request.FILES["file"] + random_str = secrets.token_urlsafe(5) + file_name, file_extension = os.path.splitext(file.name) + new_filename = f"{file_name}_{random_str}{file_extension}" + + fs = FileSystemStorage( + location=os.path.join(settings.MEDIA_ROOT, MEDIA_PATH) + ) + filename = fs.save(new_filename, file) + file_url = urljoin(settings.MEDIA_URL, os.path.join(MEDIA_PATH, filename)) + else: + form = FileUploadForm() + + return render( + request, + "custom_file_upload.html", + {"form": form, "file_url": file_url, "title": _("File Upload")}, + ) diff --git a/templates/custom_file_upload.html b/templates/custom_file_upload.html new file mode 100644 index 0000000..3b95cca --- /dev/null +++ b/templates/custom_file_upload.html @@ -0,0 +1,16 @@ +{% extends "base.html" %} + +{% block body %} +
+ {% if file_url %} +

{{_('Your file has been uploaded successfully')}}: {{ file_url }}

+ {{_('Upload another file')}} + {% else %} +
+ {% csrf_token %} + {{ form.as_p() }} + +
+ {% endif %} +
+{% endblock %} \ No newline at end of file