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
class App(models.Model):
name = models.CharField(max_length=32, unique=True)
r = models.ManyToManyField('Host')
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'^edit/$', views.edit, name="edit"),
]
views.py
# -*- coding: UTF-8 -*-
from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
from .models import *
# Create your views here.
def index(request):
hosts = Host.objects.all()
categorys = Category.objects.all()
apps = App.objects.all()
return render(request, 'index.html', locals())
@csrf_exempt
def edit(request):
host_id = request.POST.get('id2')
hostname_new = str(request.POST.get('hostname2'))
ip_new = str(request.POST.get('ip2'))
port_new = int(request.POST.get('port2'))
category_new = int(request.POST.get('category2'))
app_list_new = request.POST.getlist('app2')
res = {'status': True, 'error': None, 'data': None}
try:
Host.objects.get(id=host_id).app_set.set(app_list_new)
Host.objects.filter(id=host_id).update(hostname=hostname_new, ip=ip_new, port=port_new, category_id=category_new)
except Exception as e:
res['status'] = False
res['error'] = '更新失败'
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>IP地址</td>
<td>端口</td>
<td>操作系统类型</td>
<td>应用</td>
<td>xxx</td>
</tr>
</thead>
<tbody>
{% for host in hosts %}
<tr hid="{{ host.id }}" cid="{{ host.category_id }}" hostname="{{ host.hostname }}" ip="{{ host.ip }}" port="{{ host.port }}">
<td>{{ host.hostname }}</td>
<td>{{ host.ip }}</td>
<td>{{ host.port }}</td>
<td>{{ host.category.name }}</td>
<td>
{% for app in host.app_set.select_related %}
<span aid="{{ app.id }}">{{ app }}</span>
{% if not forloop.last %},{% endif %}
{% endfor %}
</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="mess"></span>
</div>
<!-- Modal2 -->
<div class="modal fade" id="myModal2" 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="edit_form" class="form-group" action="" method="post">
<input type="text" class="form-control" name="id2" style="display: none"><br>
hostname:<input type="text" class="form-control" name="hostname2"><br>
ipaddress:<input type="text" class="form-control" name="ip2"><br>
port:<input type="text" class="form-control" name="port2"><br>
<select id="s1" class="form-control-static" name="category2" >
{% for category in categorys %}
<option value="{{ category.id }}">{{ category }}</option>
{% endfor %}
</select>
<br>
<br>
<br>
<select id="s2" class="form-control-static" name="app2" multiple>
{% for app in apps %}
<option value="{{ app.id }}">{{ app }}</option>
{% endfor %}
</select>
</form>
</div>
<div class="modal-footer">
<button id="btn2_d" type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button id="btn2_n" type="button" class="btn btn-primary">确定</button>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="/static/js/jquery.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
var a = {{ hosts|safe }}
console.log(a);
$(".edit").click(function(){
var hid = $(this).parent().parent().attr('hid');
var hostname = $(this).parent().parent().attr('hostname');
var ip = $(this).parent().parent().attr('ip');
var port = $(this).parent().parent().attr('port');
var cid = $(this).parent().parent().attr('cid');
........把多对多的value循环加入列表........
var aid_list = [];
$(this).parent().prev().children().each(function(){
var aid = $(this).attr('aid');
aid_list.push(aid)
});
$('#edit_form input[name="id2"]').val(hid);
$('#edit_form input[name="hostname2"]').val(hostname);
$('#edit_form input[name="ip2"]').val(ip);
$('#edit_form input[name="port2"]').val(port);
$('#edit_form select[id="s1"]').val(cid);
$('#edit_form select[id="s2"]').val(aid_list);
$('#btn2_n').click(function(){
$.ajax({
url: '/edit/',
type: 'POST',
data: $('#edit_form').serialize(),
traditional: true,
success: function(data){
var obj = JSON.parse(data);
if(obj.status){
location.reload();
}else{
$('#mess').text(obj.error);
}
}
})
});
});
});
</script>
</html>
注意:
传递列表的时候ajax中一定要加:
traditional: true