【发布时间】:2015-09-30 14:36:17
【问题描述】:
我有一个显示数据的表格,我有一个带有提交按钮的表单,可以在 mysql 数据库中插入数据,我在每一行旁边添加了按钮,上面写着“删除”,这样我就可以从网站上删除每一行也是。
当我点击按钮时我得到了 id,但我还不知道如何将它传递给视图,但我现在的主要问题是第二个帖子不起作用。
template.py
<tr>
<td>{{b.ip}}</td>
<td>{{b.polling_time}}</td>
<td>{{b.communitydata}}</td>
<td>{{b.snmp_oid}}</td>
<td>{{b.lastcheck|date:"Y.m.d H:m:s"}}</td>
<form action="/services/listpoll/" method="post">{% csrf_token %}
<td><input type="button" id="{{b.id}}" class="delete_poll" value="Borrar"></td>
</form>
</tr>
jquery
$(".delete_poll").click(function(){
id_poll = $(this).attr('id');
});
views.py
def listpolls(request):
connect_mysql = mdb.connect('***', '***', '***', '***')
cursorMYSQL = connect_mysql.cursor(mdb.cursors.DictCursor)
query = "select id,ip,polling_time,communitydata,snmp_oid,lastcheck from snmptt_listpolls order by ip desc limit 100"
cursorMYSQL.execute(query)
b = cursorMYSQL.fetchall()
connect_mysql.close()
if request.method == 'POST':
form = AddPollForm(request.POST)
if form.is_valid():
ip = form.cleaned_data['poll_ip']
poll_time = form.cleaned_data['poll_time']
communitydata = form.cleaned_data['communitydata']
snmp_oid = form.cleaned_data['snmp_oid']
lastcheck = form.cleaned_data['lastcheck']
cursorMYSQL = connect_mysql.cursor(mdb.cursors.DictCursor)
cursorMYSQL.execute("""insert into snmptt_listpolls (ip, polling_time, communitydata, snmp_oid) values ('%s','%s','%s','%s')"""%(ip, poll_time, communitydata, snmp_oid))
connect_mysql.commit()
connect_mysql.close()
return HttpResponseRedirect('listpolls.html')
elif request.method == 'POST' and not form.is_valid():
id_poll = '53';
cursorMYSQL = connect_mysql.cursor(mdb.cursors.DictCursor)
cursorMYSQL.execute(""" delete from snmptt_listpolls where id='%s' """%(id_poll))
connect_mysql.commit()
connect_mysql.close()
return render_to_response("listpolls.html",{"buffer_data": b, 'form': form} )
else:
form = AddPollForm()
return render_to_response("listpolls.html",{"buffer_data": b, 'form': form} )
所以,这次我只是想检查发布请求是否有效,所以当我点击它时,它会删除 ID 为 53 的行,但它不起作用,所以我想我做错了什么并且帖子没有通过。
谢谢!
【问题讨论】:
-
完全不相关,但你到底为什么要使用
MySQLdb而不是使用内置ORM直接连接到数据库??? -
@brunodesthuilliers 这是我两天内第二次看到有人直接使用 python mysql 库,完全绕过 orm。
-
通过对用户输入使用字符串插值,不仅绕过了 orm,还绕过了 dbapi 卫生层...... Little Bobby Table 有人吗?让我们不要谈论硬编码的连接数据和无用的关闭/重新打开连接......我很惊讶操作至少使用了 django 表单
标签: jquery python mysql django