简体   繁体   English

在同一模板django中插入/删除发布请求

[英]insert / delete post requests in same template django

I have a table showing data and I have a form with a submit button that inserts data in a mysql db, I added buttons next to each row that say "delete" so I'm able to delete each row from the site too. 我有一个显示数据的表格,并且有一个带有提交按钮的表单,该表单将数据插入mysql db中,我在每行旁边添加了“删除”按钮,因此我也可以从站点中删除每一行。

I get the id when I click the button but I don't know yet how to pass it to the views, but my main problem now is that the second post isn't working. 当我单击按钮时我得到了id,但是我还不知道如何将其传递给视图,但是我现在的主要问题是第二篇文章不起作用。

template.py 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 jQuery的

$(".delete_poll").click(function(){

          id_poll = $(this).attr('id');

  });

views.py 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} ) 

So, this time I'm just trying to check if the post request is working so when I click it will delete the row with the 53 id, but it doesn't work, so I guess I'm doing something wrong and the post is not going through. 所以,这一次,我只是想检查发布请求是否正常,因此当我单击该请求时,它将删除具有53 id的行,但是它行不通,所以我想我在做错误的事情,并且发布没有经过。

Thanks! 谢谢!

I can't comment yet.So please consider it as a comment. 我目前无法发表评论,因此请视为评论。

I don't think the execution will ever reach to the second post 我认为执行不会达到第二个职位

elif request.method=="POST":

Also why don't you use Django models instead of doing it explicitly with MySQL. 另外,为什么不使用Django模型而不是通过MySQL明确地使用它。

For deleting an item you can use jquery ajax post request with the id of the item and handle it in the view. 对于删除项目,您可以使用带有该项目ID的jquery ajax post request并在视图中处理它。

Handling two (or more) different forms in a single view is no rocket science: you just need to identify which form was posted, which is easily done with a hidden input in each form. 在单个视图中处理两个(或多个)不同的表单并不是火箭科学:您只需要确定发布了哪个表单,就可以轻松地通过每个表单中的隐藏输入来完成。

 <td>
   <!-- HTML doesn't allow <form> around the <td> -->
   <form action="/services/listpoll/" method="post">
     {% csrf_token %}
     <input type="hidden" name="action" value="delete">
     <input type="hidden" name="poll_id" value="{{b.id}}">
     <input type="button" class="delete_poll" value="Borrar">
   </form>
 </td>

Now you can get rid of your useless jquery stuff and handle the deletion in the view: 现在,您可以摆脱无用的jQuery内容,并在视图中处理删除操作:

def listpolls(request): # snip MySQLdb code that has nothing to do here, # please use the orm or at least the db backend connection def listpolls(request):#截断与此无关的MySQLdb代码,#请使用orm或至少使用db后端连接

if request.method == 'POST':
    if request.post.get("action", "") == "delete":            
        # don't assume - check
        poll_id = request.post.get("poll_id", None)
        if poll_id is not None:
            delete_poll_here()
    else: 
        form = AddPollForm(request.POST)
        # etc

Now please do yourself (and whoever will have to maintain you code) a service: learn to properly use Django's ORM, and also learn to properly use Python's dbapi... This: 现在,请为您自己(以及任何需要维护您代码的人)提供一项服务:学习正确使用Django的ORM, 学习正确使用Python的dbapi ...这:

cursorMYSQL.execute(
   """insert into snmptt_listpolls 
       (ip, polling_time, communitydata, snmp_oid) 
      values ('%s','%s','%s','%s')
   """ % (ip, poll_time, communitydata, snmp_oid))

is wide open to SQL injection. 对SQL注入开放。 The correct way is 正确的方法是

cursorMYSQL.execute(
   """insert into snmptt_listpolls 
       (ip, polling_time, communitydata, snmp_oid) 
      values (%s,%s,%s,%s)
   """, (ip, poll_time, communitydata, snmp_oid))

but you really don't need this in Django when you have Models and ModelForms. 但是当您拥有Models和ModelForms时,在Django中确实不需要此功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM