【发布时间】:2015-07-07 09:39:01
【问题描述】:
我遇到过这种情况:
单击 html 提交按钮,我调用 views.stream_response,它“激活”views.stream_response_generator,它“激活”stream.py 并返回一个 StreamingHttpResponse,我看到了在/stream_response/m 每秒递增一个数字:
1
2
3
4
5
6
7
8 //e.g. my default max value for m
stream.py
from django.template import Context, Template
import time
def streamx(m):
lista = []
x=0
while len(lista) < m:
x = x + 1
time.sleep(1)
lista.append(x)
yield "<div>%s</div>\n" % x #prints on browser
print(lista) #print on eclipse
return (x)
views.py
def stream_response(request): // unified the three functions as suggested
if request.method == 'POST':
form = InputNumeroForm(request.POST)
if form.is_valid():
m = request.POST.get('numb', 8)
resp = StreamingHttpResponse(stream.streamx(m))
return resp
forms.py
from django.db import models
from django import forms
from django.forms import ModelForm
class InputNumero(models.Model):
m = models.IntegerField()
class InputNumeroForm(forms.Form):
class Meta:
models = InputNumero
fields = ('m',)
urls.py
...
url(r'^homepage/provadata/$', views.provadata),
url(r'^stream_response/$', views.stream_response, name='stream_response'),
...
主页/provadata.html
<form id="streamform" action="{% url 'stream_response' %}" method="POST">
{% csrf_token %}
{{form}}
<input id="numb" type="number" />
<input type="submit" value="to view" id="streambutton" />
</form>
如果我删除“8”并只使用m = request.POST.get('numb'),我会得到:
ValueError at /stream_response/ 视图 homepage.views.stream_response 没有返回 HttpResponse 对象。 而是返回 None。
所以,如果我尝试提交,它只需要默认值 8(并且有效),但它不需要我的表单输入。怎么了?
-->更新:@Tanguy Serrat 建议:
views.py
def stream_response(request):
form = InputNumeroForm()
if request.method == 'POST':
form = InputNumeroForm(data=request.POST)
if form.is_valid():
#Accessing the data in cleaned_data
m = form.cleaned_data['numero']
print("My form html: %s" % form)
print ("My Number: %s" % m) #watch your command line
print("m = ", m)
resp = StreamingHttpResponse(stream.streamx(m))
return resp
#If not post provide the form here in the template :
return render(request, 'homepage/provadata.html', {'form': form,})
forms.py
class InputNumeroForm(forms.Form):
numero = models.IntegerField()
主页/provadata.py
<form action="/stream_response/" method="POST">
{% csrf_token %}
{{form}} <!--issue: does not appear on the html !!!!!-->
<input type="number" name="numero" /> <!--so I write this-->
<input type="submit" value="to view" />
</form>
如果我提供输入,例如7 来自键盘:
/stream_response/ 处的 KeyError
'数字'
同时
如果我写m = request.POST.get('numero'),在命令行中我有:
...
My form html:
My Number: 7
m = 7
...
while len(lista) < m:
TypeError: unorderable types: int() < str()
【问题讨论】:
-
只是好奇为什么这一切不集中在一个函数中?另外,
stream_response_generator_bis()是在哪里定义的? -
抱歉复制粘贴时出错!没有 _bis 的 stream_response_generator()!我使用了几个函数,因为它对我来说更具可读性和可控性......我不知道如何做一个“一体化”类型的函数。
-
上面的视图是否与当前给您错误的视图相同?看起来不像。
-
不,它指的是建议。好的,我更新了视图,你是对的,谢谢。
标签: django django-forms django-views streaming httpresponse