# 1. 依赖工具类- bootstrap.py ModelForm
# 2. 依赖工具类- pagemtion.py 分页
1. 创建任务表(app-models.py)
from django.db import models
class Task(models.Model):
"""任务管理"""
level_choices = (
(1, "紧急"),
(2, "重要"),
(3, "紧急")
)
level = models.SmallIntegerField(verbose_name="级别", choices=level_choices, default=1)
title = models.CharField(verbose_name="标题", max_length=64)
detail = models.TextField(verbose_name="详细信息")
user = models.ForeignKey(verbose_name="负责人", to="Admin", on_delete=models.CASCADE) # on_delete=models.CASCADE:级联删除
# python manage.py makemigrations
# python manage.py migrate
2. 创建路由(项目-urls.py)
from bbc_list.views import login, home_page, order, phone, admin,task
urlpatterns = [
path("task/list/", task.task_list),
path("task/add/", task.task_add),]
3. 创建视图函数(app-views-task.py)
from django.shortcuts import render, HttpResponse
from bbc_list import models
from bbc_list.utils.bootstrap import BootStrapModelForm
from bbc_list.utils.pagemtion import Pagination
from django.views.decorators.csrf import csrf_exempt
class TaskModelForm(BootStrapModelForm):
class Meta:
model = models.Task
fields = "__all__"
from django import forms
widgets = {
"detail": forms.TextInput, # 输入框
# "detail": forms.Textarea 文本框
}
def task_list(request):
"""任务列表"""
# 去数据库获取所有的任务
queryset = models.Task.objects.all().order_by("-id")
# 分页
page_object = Pagination(request, queryset)
form = TaskModelForm()
context = {
"form": form,
"queryset": page_object.page_queryset,
"page_string": page_object.html()
}
return render(request, "task_list.html", context)
# 通过ajax发送post请求时,加上 @csrf_exempt 免除 csrf_token 认证
@csrf_exempt
def task_add(request):
"""ajax添加"""
# <QueryDict: {'level': ['1'], 'title': ['啦啦'], 'detail': ['哈哈'], 'user':
# ['5']}>
print(request.POST)
# 1. 用户发送过来的数据进行效验(ModelForm进行效验)
form = TaskModelForm(data=request.POST)
if form.is_valid():
form.save()
# 通过ajax发送的请求不能返回页面,只能返回json
data_dict = {"status": True}
import json
return HttpResponse(json.dumps(data_dict))
data_dict = {"status:": False, "error": form.errors}
import json # ensure_ascii=False: 中文显示错误信息
return HttpResponse(json.dumps(data_dict, ensure_ascii=False))
4. 创建html页面(templates-task_list.html)
{% extends 'one.html' %}
{% block content %}
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">表单</div>
<div class="panel-body">
<form id="formAdd">
<div class="clearfix">
{% for field in form %}
<div class="col-xs-6">
<!--style="position: relative: 相对定位; position: absolute:绝对定位-->
<div class="form-group" style="position: relative;margin-bottom:20px;">
<label>{{ field.label }}</label>
{{ field }}
<span class="error-msg" style="color:red; position: absolute"></span>
</div>
</div>
{% endfor %}
<div class="col-xs-12">
<button id="btnAdd" type="button" class="btn btn-primary">提 交</button>
</div>
</div>
</form>
</div>
</div>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
任务列表
</div>
<!-- Table -->
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>标题</th>
<th>级别</th>
<th>负责人</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for obj in queryset %}
<tr>
<th>{{ obj.id }}</th>
<th>{{ obj.title }}</th>
<th>{{ obj.get_level_display }}</th>
<!-- 多表关联 obj.字段.字段-->
<th>{{ obj.user.username }}</th>
<td>
<a class="btn btn-primary btn-xs" href="#">编辑</a>
<a class="btn btn-danger btn-xs" href="#">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<ul class="pagination">
{{ page_string }}
</ul>
</div>
{% endblock %}
{% block js %}
<script type="text/javascript">
$(function(){
//页面框架加载完后代码自动执行
bindBtnAddEvent();
})
function bindBtnAddEvent(){
$('#btnAdd').click(function(){
//点击时先将文本清空, empty() :清空
$(".error-msg").empty();
$.ajax({
url:"/task/add/",
type:"post",
data:$("#formAdd").serialize(), //会自动将表单中输入的值打包
dataType:"JSON", //将json反序列化,转换成对象
success: function(res){
//对返回的信息做判断
if (res.status) {
alert("添加成功");
//用js实现页面的刷新
location.reload()
}else{
//循环
$.each(res.error,function (name,data){
//console.log(name,data);
//("id_"+name):拼接id值
$("#id_"+name).next().text(data[0]);
})
}
}
})
})
}
</script>
{% endblock %}
标签:11,实战,task,name,models,list,任务,import,data
From: https://www.cnblogs.com/kh-1314/p/17049600.html