主要参考django-rest-framework官网教程,
rest-framework
安装项目虚拟环境中使用pip命令安装包
pip install djangorestframework
rest-framework
后端配置settings.py配置
在文件的INSTALLED_APPS
中注册rest_framework
,并根据需要选择在REST_FRAMEWORK
中添加功能。
# file:settings.py
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.course',
'rest_framework',
]
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
]
}
序列化serializers
在app文件夹中新建一个文件,命名为:serializers.py
,编写需要的序列化代码,这里以课程老师为例:
# file: course/models.py
from django.db import models
class Teacher(models.Model):
"""定义一个老师模型"""
username = models.CharField(max_length=100) # 老师名称
jobtitle = models.CharField(max_length=100) # 职位
profile = models.TextField() # 简介
avatar = models.URLField() # 图像
# file: course/serializers.py
from rest_framework import serializers
from .models import Teacher
class TeacherSerializers(serializers.ModelSerializer):
"""教师序列化"""
class Meta:
model = Teacher
fields = ("id", "username", "jobtitle", "profile", "avatar")
视图配置
# flie: course/views.py
from apps.course.models import Teacher
from apps.course.serializers import TeacherSerializers
from rest_framework import generics
class CourseTeacherList(generics.ListCreateAPIView):
"""课程老师信息的增删改查"""
queryset = Teacher.objects.all()
serializer_class = TeacherSerializers
class CourseTeacherListDetail(generics.RetrieveUpdateDestroyAPIView):
"""查找更新一个实例"""
queryset = Teacher.objects.all()
serializer_class = TeacherSerializers
路由配置
# file: course/urls.py
......
urlpatterns += [
path('course_teacher/', course_views.CourseTeacher.as_view(), name='course_teacher'),
path('course_teacher_list/', course_views.CourseTeacherList.as_view(), name='course_teacher_list'),
path('course_teacher_list//' , course_views.CourseTeacherListDetail.as_view(), name='course_teacher_list_detail'),
]
urlpatterns = format_suffix_patterns(urlpatterns)
返回参数
- application/json
- text/html
rest-framework框架默认返回的是text/html
格式,如果需要返回json或者api格式的,在路由后加上参数?format=json
或 ?format=api
.完整的url实例如下:
host: http://127.0.0.1:9000/cms/course_teacher_list/?format=json
Content-Type: application/json
response:
[{"id":1,"username":"马化腾","jobtitle":"CEO","profile":"腾讯创始人","avatar":"https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=1071899407,1665501066&fm=58&bpow=748&bpoh=1055"}]
rest-framework
前端配置使用javascript实现数据的提交、更新、获取、删除
使用template.js
模板渲染HTML数据,在使用rest-framework框架提供的数据和方法,对数据表进行get,post,put,delete等方法
HTML文件
{% block head %}
<script src="https://unpkg.com/[email protected]/dist/qiniu.min.js">script>
<script src="{% static 'js/template-web.js' %}">script>
<script src="{% static 'js/template.js' %}">script>
<script src="{% static 'js/course_teacher.js' %}">script>
{% endblock %}
{% block content %}
<div class="row">
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header">
<button id="teacher-button" type="button" class="btn btn-primary pull-right" data-toggle="modal" data-target="#exampleModal">添加教师信息button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<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="exampleModalLabel">添加老师信息h4>
div>
<div class="modal-body">
<form id="course-teacher-data" action="" method="">
<div class="form-group">
<label for="recipient-name" class="control-label">姓名:label>
<textarea type="text" class="form-control" name="teacher-name">textarea>
div><div class="form-group">
<label for="recipient-name" class="control-label">职称:label>
<textarea type="text" class="form-control" name="teacher-job-title">textarea>
div><div class="form-group">
<label for="recipient-name" class="control-label">简介:label>
<textarea class="form-control" name="teacher-profile">textarea>
div>
<div class="form-group">
<label for="form-group" class="control-label">头像:label>
<div class="input-group">
<textarea type="text" name="teacher-avatar" class="form-control" id="thumbnail-form">textarea>
<span class="input-group-btn">
<label class="btn btn-default btn-file">
上传图片 <input hidden="" type="file" class="btn btn-default" id="upload-btn">
label>
span>
div>
div>
<div class="form-group" id="progress-group" style="display: none;">
<div class="progress">
<div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar"
aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
0%
div>
div>
div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭button>
<button id="submit-btn-teacher" type="button" class="btn btn-primary">提交button>
div>
form>
div>
div>
div>
div>
div>
<div class="box-body">
<table class="table table-bordered">
<thead>
<tr>
<th>idth>
<th>姓名th>
<th>职称th>
<th>简介th>
<th>操作th>
<th>头像th>
tr>
thead>
<tbody id="course-teacher-list">
<script id="course-teacher-list-tmpl" type="text/html">
{% verbatim %}
{{ each course_teachers as teacher }}
<tr data-pk="{{ teacher.id }}" data-name="{{ teacher.username }}" data-jobtitle="{{ teacher.jobtitle }}" data-profile="{{ teacher.profile }}" data-avatar="{{ teacher.avatar }}">
<td>{{ teacher.id }}</td>
<td>{{ teacher.username }}</td>
<td>{{ teacher.jobtitle }}</td>
<td>{{ teacher.profile }}</td>
<td><img src="{{ teacher.avatar}}" alt="" style="height: 40px"></td>
<td>
<button id="edit-btn" type="button" class="btn btn-warning btn-xs edit-btn">编辑</button>
<button class="btn btn-danger btn-xs delete-btn">删除</button>
</td>
</tr>
{{ /each }}
{% endverbatim %}
script>
tbody>
table>
div>
div>
div>
div>
{% endblock %}
JavaScript文件:
// file: static/js/course_teacher.js
// 获取cookies
function getCookies(name) {
var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
return r ? r[1] : undefined;
}
// 使用七牛云上传文件
$(function (){
// ......
})
// 设置全局变量flag,用于判别submitBtnFun();函数的提交方法'post','put'
// 当flag = 0; method = 'post';
// 当flag = 1; method = 'put';
window.flag = 0;
// 数据提交方法
function submitBtnFun(event,teacherId) {
event.preventDefault();
var teacherName = $("textarea[name='teacher-name']").val();
var teacherJobTitle = $("textarea[name='teacher-job-title']").val();
var teacherProfile = $("textarea[name='teacher-profile']").val();
var teacherAvatar = $("textarea[name='teacher-avatar']").val();
var data = {
'username': teacherName,
'jobtitle': teacherJobTitle,
'profile': teacherProfile,
'avatar': teacherAvatar
};
if(teacherId !== ""){
url = '/cms/course_teacher_list/'+ teacherId + '/'
}else{
url = '/cms/course_teacher_list/'
}
if(window.flag===0){
method = 'post'
}if(window.flag === 1){
method = 'put'
}
$.ajax({
url: url,
type: method,
data: JSON.stringify(data),
contentType: "application/json",
dataType: "json",
headers: {
"X-CSRFToken": getCookies("csrftoken")
},
success: function (resp) {
if(resp){
console.log("数据提交成功!");
window.location.reload(); // 重新加载当前界面
}else{
console.log("添加老师信息失败!");
}
}
});
}
// 老师信息js渲染方法
function getTeacherInfo () {
$.get("/cms/course_teacher_list/?format=json", function (resp) {
if(resp){
$("#course-teacher-list").html(template("course-teacher-list-tmpl", {course_teachers:resp}));
}else {
console.log("django-rest-framework没有返回数据!");
}
});
}
// 获取老师信息
$(document).ready(function () {
getTeacherInfo();
// 添加老师信息
$(function addTeacher () {
$("#submit-btn-teacher").click(function () {
submitBtnFun(event, '');
})
});
// 编辑老师信息
$(function editTeacher () {
$("body").on('click',".edit-btn",function () {
window.flag = 1; // 设置全局变量flag=1,用于判别提交方法为'put'
var currentBtn = $(this);
// 获取当前老师信息
var tr = currentBtn.parent().parent();
var teacherId = tr.attr('data-pk');
var teacherName = tr.attr('data-name');
var teacherJobTitle = tr.attr('data-jobtitle');
var teacherProfile = tr.attr('data-profile');
var teacherAvatar = tr.attr('data-avatar');
// // 获取编辑from表单各标签信息
var teacherNameFrom = $("textarea[name='teacher-name']");
var teacherJobTitleFrom = $("textarea[name='teacher-job-title']");
var teacherProfileFrom = $("textarea[name='teacher-profile']");
var teacherAvatarFrom = $("textarea[name='teacher-avatar']");
var formTitle = $('#exampleModalLabel');
formTitle.value = "修改老师信息";
teacherNameFrom.html(value = teacherName);
teacherJobTitleFrom.html(value = teacherJobTitle);
teacherProfileFrom.html(value = teacherProfile);
teacherAvatarFrom.html(value = teacherAvatar);
$('#teacher-button').click();
$('#submit-btn-teacher').click(function () {
submitBtnFun(event,teacherId);
});
});
});
// 删除老师信息
$(function () {
$("body").on('click',".delete-btn",function () {
var currentBtn = $(this);
var tr = currentBtn.parent().parent();
var teacherId = tr.attr('data-pk');
xfzalert.alertConfirm({
'text': '确定删除该老师的信息吗?',
// 如果确定执行函数
'confirmCallback':function () {
$.ajax({
url: '/cms/course_teacher_list/' + teacherId + '/',
type: 'delete',
contentType: 'application/json',
headers: {
"X-CSRFToken": getCookies('csrftoken')
},
success: function () {
console.log("删除成功!");
window.location.reload();
},
fail: function () {
console.log("删除数据失败!")
}
})
}
});
})
});