[Solved]-Render current status only on template in StreamingHttpResponse in Django

10👍

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

-2👍

def f1():
    x = 1
    while x < 5:
        time.sleep(1)
        x += 1
        s = str()
        for i in range(1,x):
            s+= """<p>{}</p>""".format(str(i))
        code = s
        yield code

I think like this…

def home(request):
     for z in f1():
         return StreamingHttpResponse(z)

Leave a comment