我试图从Django中的表单发布数据,当我点击提交时,它没有进入POST。我已经使用Django完成了一些POST,他们工作正常。这里,第一次呈现模板时,它进入NO POST,这是正确的。但是,在提交表单时,它表示无效。
urls.py
url(r'^traps/view/', 'servicios.views.viewtraps'),
forms.py
class LimitQueryForm(forms.Form):
limit = forms.CharField(label='Nº de Resultados a Mostrar', max_length=250)
模板
<form action="/services/traps/view/" method="post">{% csrf_token %}
{{ form_limit }}
<button type="submit" value="btn_limit_val" name="btn_limit_name">Aceptar</button>
</form>
views.py
def viewtraps(request):
connect_mysql = mdb.connect(*)
cursorMYSQL = connect_mysql.cursor(mdb.cursors.DictCursor)
cursorMYSQL.execute("""select eventname,eventid,trapoid,enterprise,community,hostname,agentip,category,severity,uptime,traptime,formatline,timestamp from snmptt order by id desc limit 500""")
b = cursorMYSQL.fetchall()
connect_mysql.close()
form_limit = LimitQueryForm()
if request.method == 'POST':
if form_limit.is_valid():
limit = "VALID"
dictionary = RequestContext(request, {"buffer_data": b, "form_limit": form_limit, "limit": limit})
return render_to_response("viewtraps.html", dictionary)
else:
limit = "NOT VALID"
dictionary = RequestContext(request, {"buffer_data": b, "form_limit": form_limit, "limit": limit})
return render_to_response("viewtraps.html", dictionary)
else:
limit = "NO POST"
dictionary = RequestContext(request, {"buffer_data": b, "form_limit": form_limit, "limit": limit})
return render_to_response("viewtraps.html", dictionary)
我知道有些用户告诉我,我不应该这样使用django,我有理由这样做,请避免评论,因为它不是问题马上。谢谢!
答案 0 :(得分:0)
问题在于form_limit
的初始化,它是在不读取请求参数的情况下创建的。请尝试改为:
if request.method == 'POST':
form_limit = LimitQueryForm(request.POST)
...
else:
form_limit = LimitQueryForm()
供参考:https://docs.djangoproject.com/en/1.8/topics/forms/#the-view
答案 1 :(得分:0)
吸尘器..
def viewtraps(request):
# ... db connections
form_limit = LimitQueryForm(request.POST or None) #<--- this was your typo
if form_limit.is_valid():
limit = "VALID"
dictionary = RequestContext(request, {"buffer_data": b, "form_limit": form_limit, "limit": limit})
return render_to_response("viewtraps.html", dictionary)
else:
limit = "NOT VALID"
dictionary = RequestContext(request, {"buffer_data": b, "form_limit": form_limit, "limit": limit})
return render_to_response("viewtraps.html", dictionary)
dictionary = RequestContext(request, {"buffer_data": b, "form_limit": form_limit, "limit": limit})
return render_to_response("viewtraps.html", dictionary)