删除主机
2017-07-11 本文已影响0人
赖三石
ajax 方式
urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index, name="index"),
url(r'^del/$', views.ajax_del_host, name="ajax_del_host"),
]
view.py
# -*- coding: UTF-8 -*-
from .models import *
from django.shortcuts import render, HttpResponse
import json
# Create your views here.
def index(request):
hosts = Host.objects.all()
categorys = Category.objects.all()
return render(request, 'index.html', {'hosts': hosts, 'categorys': categorys})
def ajax_del_host(request):
res = {'status': True, 'mess': None, 'data': None}
hid = request.POST.get('hid')
print "-------------hid"
try:
host_one = Host.objects.get(id=hid)
host_one.delete()
except Exception as e:
res['status'] = False
res['mess'] = '删除失败'
return HttpResponse(json.dumps(res))
template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<table class="table table-bordered">
<thead>
<tr>
<td>序号</td>
<td>cid</td>
<td>name</td>
<td>ip</td>
<td>port</td>
<td>category</td>
<td>xxx</td>
<td>xxx</td>
</tr>
</thead>
<tbody>
{% for host in hosts %}
<tr hid="{{ host.id }}" cid="{{ host.category_id }}" hostname2="{{ host.hostname }}" ip2="{{ host.ip }}" port2="{{ host.port }}">
<td>{{ forloop.counter }}</td>
<td>{{ host.category_id }}</td>
<td>{{ host.hostname }}</td>
<td>{{ host.ip }}</td>
<td>{{ host.port }}</td>
<td>{{ host.category.name }}</td>
<td><a class="del">删除</a></td>
<td><button type="button" class="btn btn-primary btn-sm edit" data-toggle="modal" data-target="#myModal2">编辑</button></td>
</tr>
{% endfor %}
</tbody>
</table>
<span id="error"></span>
</div>
</div>
</body>
<script src="/static/js/jquery.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$('.del').click(function(){
var hid = $(this).parent().parent().attr('hid');
$.ajax({
url: '{% url 'ajax_del_host' %}',
type: 'POST',
data: {csrfmiddlewaretoken: '{{ csrf_token }}', 'hid': hid},
{# data: $('#aform').serialize(),#}
success: function(data){
var res = JSON.parse(data);
if(res.status){
location.reload();
}else{
$('#error').text(res.mess);
}
}
})
});
});
</script>
</html>
url方式
见(jquery的ajax) http://www.jianshu.com/p/182333764ac7