简体   繁体   中英

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.

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.

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} ) 

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.

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.

For deleting an item you can use jquery ajax post request with the id of the item and handle it in the view.

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:

def listpolls(request): # snip MySQLdb code that has nothing to do here, # please use the orm or at least the db backend connection

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:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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