Add custom file upload

This commit is contained in:
cuom1999 2024-03-22 22:52:21 -05:00
parent 680de724ba
commit 44c4795282
3 changed files with 61 additions and 0 deletions

View file

@ -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<contest>\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"):

View file

@ -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")},
)

View file

@ -0,0 +1,16 @@
{% extends "base.html" %}
{% block body %}
<center>
{% if file_url %}
<p>{{_('Your file has been uploaded successfully')}}: <a href="{{ file_url }}" target="_blank">{{ file_url }}</a></p>
<a href="{{ url('custom_file_upload') }}" class="button small" style="width: fit-content;">{{_('Upload another file')}}</a>
{% else %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p() }}
<button type="submit">{{_('Upload file')}}</button>
</form>
{% endif %}
</center>
{% endblock %}