ajax方式
models.py
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Host(models.Model):
hostname = models.CharField(max_length=32, unique=True)
ip = models.GenericIPAddressField(max_length=20, unique=True)
port = models.IntegerField()
category = models.ForeignKey('Category')
def __unicode__(self):
return self.hostname
class Category(models.Model):
name = models.CharField(max_length=32, unique=True)
def __unicode__(self):
return self.name
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"),
url(r'^create_host/$', views.ajax_create_host, name="ajax_create_host"),
]
views.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))
def ajax_create_host(request):
res = {'status': True, 'error': None, 'data': None}
hostname = request.POST.get('hostname')
ip = request.POST.get('ip')
port = request.POST.get('port')
category = request.POST.get('category')
try:
if hostname and len(hostname) > 5:
host_one = Host.objects.create(hostname=hostname, ip=ip, port=port, category_id=category)
host_one.save()
else:
res['status'] = False
res['error'] = '格式不正确'
except Exception as e:
res['status'] = False
res['error'] = '添加失败'
# print(hostname,ip,port,category)
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>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal1">
创建主机
</button>
<!-- Modal1 -->
<div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">创建主机</h4>
</div>
<div class="modal-body">
<form id="aform" class="form-group" action="" method="post">
hostname:<input id="hostname" type="text" class="form-control" name="hostname"><br>
ipaddress:<input id="ip" type="text" class="form-control" name="ip"><br>
port:<input id="port" type="text" class="form-control" name="port"><br>
<select id="category" name="category" class="form-control-static">
{% for category in categorys %}
<option value="{{ category.id }}">{{ category }}</option>
{% endfor %}
</select>
</form>
</div>
<div class="modal-footer">
<button id="btn1_d" type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button id="btn1" type="button" class="btn btn-primary">确定</button>
</div>
</div>
</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);
}
}
})
});
$('#btn1').click(function(){
$.ajax({
url: '/create_host/',
type: 'POST',
data: {csrfmiddlewaretoken: '{{ csrf_token }}','hostname':$('#hostname').val(),'ip': $('#ip').val(), 'port': $('#port').val(), 'category': $('#category').val()},
{# data: $('#aform').serialize(),#}
success: function(data){
var obj = JSON.parse(data);
if(obj.status){
location.reload();
}else{
$('#btn1_d').trigger('click');
$('#error').text(obj.error);
}
}
})
});
});
</script>
</html>
网友评论