'upload a file and get celery progress bar using ajax in django
I want to upload a file, process it in a Celery task, and show a progress bar using AJAX. but I did not get the solution. Can you help me with this task?
Views.py
# Create your views here.
def index(request):
if request.method == 'POST':
myfile =request.FILES['file']
fs = FileSystemStorage()
filename = fs.save(myfile.name , myfile)
uploaded_file_url = fs.url(filename)
data = process_file.delay(myfile.name)
task_id=data.task_id
return render(request , 'index.html', context={'task_id':task_id})
else:
return render(request , 'index.html')
task.py
def task_status(request, task_id):
if 'task' in request.GET:
task_id = request.GET['task_id']
else:
return HttpResponse('no job id given')
task = AsyncResult(task_id)
data = {
'state': task.state,
'result': task.result,
}
return HttpResponse(json.dumps(data), content_type='application/json')
# return render(request, 'progress.html', data)
Task.py
@shared_task(bind=True)
def process_file(self, file_name):
print('Uploading image...')
progress_recorder = ProgressRecorder(self)
result = 0
for i in range(5):
time.sleep(1)
result += i
instance = Tooltype(image=file_name)
instance.save()
#fs.delete(file_name)
print('Uploaded!')
progress_recorder.set_progress(i + 1, 5)
return result
index.html
<body>
<h1>select your file to process it!</h1>
<div class='progress-wrapper'>
<div id='progress-bar' class='progress-bar' style="background-color: #68a9ef; width: 0%;"> </div>
</div>
<div id="progress-bar-message">Waiting for progress to start...</div>
<form id="process-raw-data" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" id="file" name="file" >
<button type="submit" class="btn btn-success">Submit</button>
</form>
{% if task_id %}
<script>
var progressUrl = "{% url 'celery_progress:task_status' task_id %}";
function customResult(resultElement, result) {
$( resultElement ).append(
$('<p>').text('Sum of all seconds is ' + result)
);
}
$(function () {
CeleryProgressBar.initProgressBar(progressUrl, {
onResult: customResult,
})
});
</script>
{% endif %}
<script src="{% static 'celery_progress/celery_progress.js' %}"></script>
<script src="{% static 'assets/js/main.js' %}"></script>
</body>
when i upload a file and click on submit button it shows the progress bar but the file not shown in page and the task is successed and image is not uploading and show on page.
[2022-04-20 15:37:52,815: INFO/MainProcess] Task toolapp.tasks.process_file[b219aba3-d170-49e2-925c-3ad1c0a7c54b] succeeded in 5.327999999979511s: 10
thanks and got stuck on this task please help me.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
