1,创建project
2,settings中添加
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
)
创建‘static’目录,加入JS
3,models
from django.db import models
class Classes(models.Model):
"""
班级表,男
"""
title = models.CharField(max_length=32)
m = models.ManyToManyField("Teachers")
class Teachers(models.Model):
"""
老师表,女
"""
name = models.CharField (max_length=32)
class Student(models.Model):
username = models.CharField(max_length=32)
age = models.IntegerField()
gender = models.BooleanField()
cs = models.ForeignKey(Classes,on_delete=models.CASCADE)
4,运行python manage.py makemigrations
python manage.py migrate
5,url.py
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('students/',views.students),
path('add_student/',views.add_student),
path('del_student/',views.del_student)
]
views.py
from django.shortcuts import render,HttpResponse
from app01 import models
import json
def students(request):
cls_list = models.Classes.objects.all()
stu_list = models.Student.objects.all()
return render(request,'students.html',{'stu_list':stu_list,'cls_list':cls_list})
def add_student(request):
response = {'status':True,'message':None,'data':None}
try:
print(request.POST)
u = request.POST.get('username')
a = request.POST.get('age')
g = request.POST.get('gender')
c = request.POST.get('cls_id')
obj= models.Student.objects.create(
username=u,
age=a,
gender=g,
cs_id=c
)
response['data'] = obj.id #向前端返回ID以便前端删除数据
except Exception as e:
response['status']=False
response['message']='用户输入错误'
result = json.dumps(response,ensure_ascii=False)
return HttpResponse(result)
def del_student(request):
ret = {'status':True}
try:
nid = request.GET.get('nid')
models.Student.objects.filter(id=nid).delete()
except Exception as e:
ret['status':False]
return HttpResponse(json.dumps(ret))
students.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css">
<link rel="stylesheet" href="/static/plugins/font-awesome/css/font-awesome.css">
</head>
<body>
<div class="container">
<div>
<a class="btn btn-primary" id="addBtn">添加记录</a>
</div>
<div>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>班级</th>
<th>操作</th>
</tr>
</thead>
<tbody id="tb">
{% for row in stu_list %}
<tr nid="{{ row.id }}">
<td>{{ row.id }}</td>
<td>{{ row.username }}</td>
<td>{{ row.age }}</td>
<td>{{ row.gender }}</td>
<td>{{ row.cs.title }}</td>
<td>
<a class="fa fa-pencil-square-o"></a>
<a class="glyphicon glyphicon-remove del-row"></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="addModal" 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 class="form-horizontal">
<div class="form-group">
<label for="username" class="col-sm-2 control-label">姓名</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="username" placeholder="姓名">
</div>
</div>
<div class="form-group">
<label for="age" class="col-sm-2 control-label">年龄</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="age" placeholder="年龄">
</div>
</div>
<div class="form-group">
<label for="gender" class="col-sm-2 control-label">性别</label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="gender" value="1"> 男
</label>
<label class="radio-inline">
<input type="radio" name="gender" value="0"> 女
</label>
</div>
</div>
<div class="form-group">
<label for="class" class="col-sm-2 control-label">班级</label>
<div class="col-sm-10">
<select class="form-control" name="cls_id">
{% for row in cls_list %}
<option value="{{ row.id }}">{{ row.title }}</option>
{% endfor %}
</select>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<span id="errorMsg" style="color:red"></span>
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary" id="btnSave">保存</button>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="alert alert-danger" role="alert">
<h3>删除学生信息?</h3>
<div>...<input style="display: none;" type="text" id="delNid" /></div>
<div>
<button type="button" class="btn btn-default">取消</button>
<button id="delConfirm" type="button" class="btn btn-danger">确定</button>
</div>
</div>
</div>
</div>
<script src="/static/js/jquery-3.3.1.js"></script>
<script src="/static/plugins/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
<script>
$(function () {
bindEvent();
bindSave();
bindDel();
bindDelConfirm();
});
function bindDelConfirm() {
$('#delConfirm').click(function () {
var rowId = $('#delNid').val();
console.log(rowId);
$.ajax({
url: '/del_student/',
type: 'GET',
data: {'nid': rowId},
success:function (arg) {
var dict = JSON.parse(arg);
if(dict.status){
$('tr[nid="'+ rowId+'"]').remove();
}
$('#delModal').modal('hide');
}
})
});
}
function bindDel() {
$('.del-row').click(function () {
$('#delModal').modal('show');
// 获取当前行的ID
var rowId = $(this).parent().parent().attr('nid');
$('#delNid').val(rowId);
})
}
function bindEvent() {
$('#addBtn').click(function () {
$('#addModal').modal('show');
})
}
function bindSave() {
$('#btnSave').click(function () {
var postData = {};
$('#addModal').find('input,select').each(function () {
var v = $(this).val();
var n = $(this).attr('name');
if(n=='gender'){
if($(this).prop('checked')){
postData[n] = v;
}
}else{
postData[n] = v;
}
});
/*
postData = {
username: 'asdf',
age:18,
gender: 1,
cls_id: 2
}
*/
$.ajax({
url: '/add_student/',
type: 'POST',
data: postData,
success:function (arg) {
// arg是字符串
// JSON.parse将字符串转换成字典, json.loads
var dict = JSON.parse(arg);
if(dict.status){
/*
postData = {
username: 'asdf',
age:18,
gender: 1,
cls_id: 2
}
自增id = dict.data
*/
createRow(postData,dict.data);
$('#addModal').modal('hide');
// window.location.reload();
}else {
$('#errorMsg').text(dict.message);
}
}
})
});
}
function createRow(postData,nid) {
var tr = document.createElement('tr');
var tdId = document.createElement('td');
tdId.innerHTML = nid;
$(tr).append(tdId);
var tdUser = document.createElement('td');
tdUser.innerHTML = postData.username;
$(tr).append(tdUser);
var tdAge = document.createElement('td');
tdAge.innerHTML = postData.age;
$(tr).append(tdAge);
var tdGender = document.createElement('td');
if(postData.gender == "0"){
tdGender.innerHTML = 'False';
}else{
tdGender.innerHTML = 'True';
}
$(tr).append(tdGender);
var tdClass = document.createElement('td');
var text = $('select[name="cls_id"]').find('option[value="'+ postData.cls_id +'"]').text();
tdClass.innerHTML = text;
$(tr).append(tdClass);
var tdHandle = '<td> <a class="glyphicon glyphicon-remove icon"></a><a class="fa fa-pencil-square-o icon"></a> </td>';
$(tr).append(tdHandle);
$('#tb').append(tr);
}
</script>
</body>
</html>
新增标签需要使用事件委托:
$('要绑定标签的上级标签').on('click','要绑定的标签',function(){})
$('要绑定标签的上级标签').delegate('click','要绑定的标签',function(){})
修改位置1:
function bindDel() {
$('#tb').on('click','.del-row',function () {
//$('.del-row').click(function () {
$('#delModal').modal('show');
// 获取当前行的ID
var rowId = $(this).parent().parent().attr('nid');
$('#delNid').val(rowId);
})
修改位置2:
var tdHandle = '<td><a class="fa fa-pencil-square-o icon"></a> <a class="glyphicon glyphicon-remove icon del-row"></a> </td>';
修改位置3:
var tr = document.createElement('tr');
$(tr).attr('nid',nid);
编辑功能
新建一个模态对话框
URL
views
def edit_student(request):
response ={'code':1000,'message':None}
try:
nid = request.POST.get('nid')
user = request.POST.get('user')
age = request.POST.get('age')
gender = request.POST.get('gender')
cls_id = request.POST.get('cls_id')
models.Student.objects.filter(id=nid).update(
username=user,
age=age,
gender=gender,
cs_id=cls_id
)
except Exception as e:
response['code'] = 1001
response['message'] =str(e)
return HttpResponse(json.dumps(response))
html再增加
$(function () {
bindEvent();
bindSave();
bindDel();
bindDelConfirm();
bindEdit();
bindEditConfirm();
});
function bindEditConfirm() {
$('#btnEditSave').click(function () {
var postData = {};
$('#editModal').find('input,select').each(function () {
var v = $(this).val();
var n = $(this).attr('name');
if (n == 'gender') {
if ($(this).prop('checked')) {
postData[n] = v;
}
} else {
postData[n] = v;
}
});
$.ajax({
url: '/edit_student/',
type: 'POST',
data: postData,
dataType: 'JSON', //解析返回可序列化数据。否则报错
success: function (arg) {
if (arg.code == 1000) {
window.location.reload();
} else {
alert(arg.message);
}
}
})
})
}
改进:
function bindEditConfirm() {
$('#btnEditSave').click(function () {
$.ajax({
url: '/edit_student/',
type: 'POST',
data: $('#fm').serialize(),
dataType: 'JSON', //解析后端返回可序列化数据。否则报错。
success: function (arg) {
if (arg.code == 1000) {
window.location.reload();
} else {
alert(arg.message);
}
}
})
})
}