Есть ли способ заставить мою html-страницу обновляться/перезагружаться после завершения работы функции во вкладке django view.py?
Я хочу, чтобы моя страница обновлялась сама после успешной загрузки zip-файла, поскольку последовательные попытки нажать на кнопку отправки приводят к ошибке, и единственный способ устранить ее довольно легко - вручную обновить/перезагрузить страницу. Мне интересно, есть ли способ настроить его так, чтобы после завершения загрузки zip-файла страница обновлялась сама по себе без необходимости беспокоиться об этом пользователю. Делая это таким образом, я также убиваю двух зайцев одним выстрелом, так как я хочу отключить кнопку отправки, чтобы предотвратить спам пользователей, но если я в конечном итоге обновлю страницу, я смогу просто удалить ее после нажатия.
Вот мой HTML код:
{% load static %}
<html>
<head>
<link rel="stylesheet" href="{% static '/styleSheet.css' %}">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edstore">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--BOOTSTRAP ASSETS-->
<link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@400;700&display=swap" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<form enctype="multipart/form-data" action="" method="post">
{% csrf_token %}
<div class="main_Body">
<div class="section">
<h1>Fileconverter</h1>
<br>
<label for="file_field" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i>Updload File(s)</label>
<input type="FILE" id="file_field" name="file_field" class="file-upload_button" multiple>
<label id="file_name"></label>
<br>
<br><br><br>
<br>
<button type="submit" class="file-submit__button" onclick="formDisableButton()" id="submitButton">Testing</button> <!--onclick="formDisableButton"-->
</div>
</form>
</body>
<footer>
<p>Click "Choose File(s)" and select the files you want to convert.</p>
<p>Once you click "Submit" the job will start.</p>
<p>Upon completion, a zip folder will be downloaded in your browser.</p>
<p>Do not click the submit buttons multiple times. If the tab is loading, the job is being processed.</p>
</footer>
</html>
<script>
document.querySelector("#file_field").onchange = function(){
document.querySelector("#file_name").textContent = this.files[0].name;
}
const tempButton = document.getElementById("submitButton");
function formDisableButton(){
// tempButton.disabled = true;
// setTimeout(formEnableButton, 10000);
location.reload();
}
function formEnableButton(){
tempButton.disabled = false;
}
/*setTimeout(()=>{
btn.disabled = false;
console.log('Button Activated')
}, 10000)*/
/* $(function(){
$("#submitButton").click(function(){
$("#submitButton").attr("disabled", "disabled");
setTimeout(function(){
$("#submitButton").removeAttr("disabled");
}, 10000)
});
});*/
</script>
А вот файл views.py:
from django.shortcuts import render
from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic.edit import FormView
from django.views.decorators.csrf import csrf_exempt
from .forms import FileFieldForm
from django.http import HttpResponse
from .perform_conversion import FileConverter
import zipfile
import io
def FileFieldFormView(request, *args, **kwargs):
form = FileFieldForm(request.POST)
files = request.FILES.getlist('file_field')
if request.method == 'POST':
form = FileFieldForm(request.POST, request.FILES)
if form.is_valid():
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w", False) as zip_file:
for f in files:
fileconverter = FileConverter(f.name)
fileconverter.run(f.file)
for img_name, img in fileconverter.output.items():
data = io.BytesIO(img)
zip_file.writestr(img_name, data.getvalue())
# Set the return value of the HttpResponse
response = HttpResponse(zip_buffer.getvalue(), content_type='application/octet-stream')
# Set the HTTP header for sending to browser
response['Content-Disposition'] = "attachment; filename=%s" % 'zip.zip'
response.set_signed_cookie('csrftoken', request.COOKIES['csrftoken'])
# Return the response value
return response
else:
return HttpResponse('Form Invalid')
else:
return render(request, 'pages/file_converter.html')
Основываясь на том, что я увидел, покопавшись перед тем, как задать этот вопрос, Ajax кажется правильным направлением, но у меня нет опыта работы с ним, и все, что я нашел в Интернете, кажется, не применимо к типу вопроса, который я задаю. Также не работает onclick для кнопки отправки, но это не главная проблема сейчас. TBH любая помощь будет очень признательна!
Используйте javascript onclick
, чтобы изменить класс кнопки с class="file-submit__button"
на что-то вроде class="file-submit__button-disabled"
, и, конечно, добавьте соответствующий css.