9👍
✅
Yes, but it may not be what you really want, as the entire template will be iterated. However, for what it’s worth, you can stream a re-rendered context for a template.
from django.http import StreamingHttpResponse
from django.template import Context, Template
# Template code parsed once upon creation, so
# create in module scope for better performance
t = Template('{{ mydata }} <br />\n')
def gen_rendered():
for x in range(1,11):
c = Context({'mydata': x})
yield t.render(c)
def stream_view(request):
response = StreamingHttpResponse(gen_rendered())
return response
EDIT:
You can also render a template and just append <p>
or <tr>
tags to it, but it’s quite contrary to the purpose of templates in the first place. (i.e. separating presentation from code)
from django.template import loader, Context
from django.http import StreamingHttpResponse
t = loader.get_template('admin/base_site.html') # or whatever
buffer = ' ' * 1024
def gen_rendered():
yield t.render(Context({'varname': 'some value', 'buffer': buffer}))
# ^^^^^^
# embed that {{ buffer }} somewhere in your template
# (unless it's already long enough) to force display
for x in range(1,11):
yield '<p>x = {}</p>{}\n'.format(x, buffer)
Source:stackexchange.com