Как заставить html-страницу обновляться после завершения функции django?
Я продолжаю получать ошибку, связанную с токеном csrf, когда я пытаюсь использовать последовательные представления, и обновление страницы, кажется, работает. Цель программы - создание zip-файлов, поэтому я решил, что самым простым решением будет автоматическая перезагрузка веб-страницы после того, как zip-файл будет создан с помощью функции в файле views.py и доступен пользователю для открытия. Основная проблема, с которой я столкнулся, заключается в том, как на самом деле это сделать.
Вот код для моего 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>
<input type="submit" class="file-submit__button" id="submitButton"> <!--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);
}
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)
});
});*/
А это код из моего файла 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':
print(request)
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, 'file_converter.html')
В качестве бонуса, если вы готовы оказать дополнительную помощь, я не могу сделать так, чтобы у моей кнопки отправки был какой-то onclick. Каждый раз, когда я пытаюсь добавить ее, файлы python никогда не запускаются, и страница просто сидит на месте. Я хотел бы сделать так, чтобы при нажатии на кнопку отправки она удалялась со страницы, чтобы предотвратить чрезмерные попытки отправки, а поскольку, теоретически, страница будет обновляться после успешного выполнения, кнопка отправки будет просто повторно размещена на странице.