I was trying to display the status of processing to the user on the front end when I was using StreamingHttpResponse.
I was able to get the current status but it is being appended to the previous one.
I want the response template to contain only the current yield.
views.py
from django.shortcuts import render
from django.http import StreamingHttpResponse,HttpResponse
import time
def f1():
x = 0
while x<5:
time.sleep(1)
x = x+1
code = """<p>{}</p>""".format(x)
yield code
def home(request):
return StreamingHttpResponse(f1())
output in the browser
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
expected output
1st: <p>1</p>
2nd: <p>2</p>
instead of <p>1</p><p>2</p>
3rd: <p>3</p>
instead of <p>1</p><p>2</p><p>3</p>
4th: <p>4</p>
instead of <p>1</p><p>2</p>3<p></p>4<p></p>
instead of appending the previous yield I want the template to be filled with the current yield.
You can't do it this way.
def home(request):
return StreamingHttpResponse(f1())
A StreamingHttpResponse
means you want to stream data slowly instead of one go. Now once you have placed the <p>1</p>
on the stream, you can't just call it back and make it vanish
So you have few options on how to get it to work.
AJAX
You can from the page make a AJAX call which updates the latest status and you update the same using javascript
In this too you can use your existing setup with
jQuery read AJAX stream incrementally?
And then display the last line, I won't recommend this though
Next is to make a Ajax method which only returns current status
Socket.io
You can use the django-socketio for the same
Django Channels
You can use django-channels
But add sockets
and channels
would be a add-on complexity for your problem. So you should try to solve your with pure AJAX
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With