您的位置:首页 > 编程语言 > Go语言

Django实现删除课程方法——Ajax

2019-01-05 15:54 806 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/85855772

一 删除基本流程

1 单击删除

2 弹出确认框

3 单击确认

4 提交数据

5 返回结果并跳转/刷新页面

二 重写视图类

[code]# 引入ListView
from django.views.generic import TemplateView, ListView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.views.generic.edit import CreateView
from django.shortcuts import redirect
import json
from django.http import HttpResponse

from .forms import CreateCourseForm
from .models import Course

from braces.views import LoginRequiredMixin

class AboutView(TemplateView):
template_name = "course/about.html"

# 继承ListView
class CourseListView(ListView):
# 被类所使用的数据模型,能够得到数据表中的所有记录
model = Course
# 传入模板的变量名称
context_object_name = "courses"
# 模板文件
template_name = 'course/course_list.html'

class UserMixin:
def get_queryset(self):
qs = super(UserMixin, self).get_queryset()
return qs.filter(user=self.request.user)

# 增加一个继承类LoginRequiredMixin,用于判断是否登录
class UserCourseMixin(UserMixin, LoginRequiredMixin):
model = Course
# 声明用户登录URL
login_url = "/account/login/"

class ManageCourseListView(UserCourseMixin, ListView):
context_object_name = "courses"
template_name = 'course/manage/manage_course_list.html'

# 当用户以GET方式请求时,即在页面显示表单,CreateView就是完成这个作用的类
# 只要继承它,就不需要写get()方法了。
class CreateCourseView(UserCourseMixin, CreateView):
# 声明在表单中显示的字段
fields = ['title', 'overview']
template_name = 'course/manage/create_course.html'

def post(self, request, *args, **kargs):
form = CreateCourseForm(data=request.POST)
if form.is_valid():
new_course = form.save(commit=False)
new_course.user = self.request.user
new_course.save()
# 当表单内容被保存后,将页面转向指定位置
return redirect("course:manage_course")
# 当表单数据检测不通过时,让用户重新填写
return self.render_to_response({"form":form})

# 继承了DeleteView类后,后续代码就不需要重复删除动作了
# 只需要声明确认删除模板template_name和删除完成之后的界面success_url
class DeleteCourseView(UserCourseMixin, DeleteView):
template_name = 'course/manage/delete_course_confirm.html'
success_url = reverse_lazy("course:manage_course")

def dispatch(self, *args, **kwargs):
resp = super(DeleteCourseView, self).dispatch(*args, **kwargs)
# 如果是Ajax方法提交过来的数据,就直接反馈HttpResponse对象给前端
if self.request.is_ajax():
response_data = {"result": "ok"}
return HttpResponse(json.dumps(response_data), content_type="application/json")
else:
return resp

三 重写前端模板

[code]{% extends "article/base.html" %}
{% load staticfiles %}
{% block title %}管理课程{% endblock %}

{% block content %}
<div>
<div class='text-right'><a href="{% url 'course:create_course' %}"><button type="button" class="btn btn-primary">添加课程</button></a></div>
<table class="table table-hover" style="margin-top:10px">
<tr>
<td>序号</td>
<td>课程标题</td>
<td>发布日期</td>
<td>操作</td>
</tr>
{% for course in courses %}
<tr id={{ forloop.counter }}>
<td>{{ forloop.counter }}</td>
<td>{{ course.title }}</a></td>
<td>{{ course.created|date:"Y-m-d" }}</td>
<td>
<a name="edit" href="#"><span class="glyphicon glyphicon-pencil"></span></a>
<a class="delete" nane="delete" href="{% url 'course:delete_course' course.id %}" ><span class="glyphicon glyphicon-trash" style="margin-left:20px;"></span></a>
<a href="#"><span class="glyphicon glyphicon-search" style="margin-left:20px;"></span></a>
</td>
</tr>
{% endfor %}
</table>
</div>
<script type="text/javascript" src='{% static "js/jquery.js" %}'></script>
<script type="text/javascript">
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
$(document).ready(function() {
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
var onDelete = function(){
alert("确实要删除吗?");
$.post(this.href, function(data) {
// 前端得到反馈结果,就完成了删除和页面刷新
if (data.result == "ok"){
window.location.reload();
} else {
alert("出现了一些问题");
}
}).fail(function() {
alert("error");
});
return false;
}
$(".delete").click(onDelete);
})
</script>
{% endblock %}

四 测试效果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: