一 重写课程类
class Course(models.Model):
user = models.ForeignKey(User, related_name='courses_user')
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True)
overview = models.TextField()
created = models.DateTimeField(auto_now_add=True)
# 课程和学生是多对多的关系
student = models.ManyToManyField(User, related_name="courses_joined", blank=True)
class Meta:
ordering = ('-created',)
def save(self, *args, **kargs):
self.slug = slugify(self.title)
super(Course, self).save(*args, **kargs)
def __str__(self):
return self.title
二 编写视图类
# 该类继承课程内容列表类
class StudentListLessonView(ListLessonsView):
# 重写模板
template_name = "course/slist_lessons.html"
# 前端Ajax提交的处理,将课程和学生的对应关系记录到数据库
def post(self, request, *args, **kwargs):
course = Course.objects.get(id=kwargs['course_id'])
course.student.add(self.request.user)
return HttpResponse("ok")
三 创建模板文件
{% extends "base.html" %}
{% load staticfiles %}
{% block title %}课程列表{% endblock %}
{% block content %}
<div class="container">
<div class='text-center'>
<h1>{{ course.title }}</h1>
<p>课程内容列表</p>
<form action="." method="post" class="form-horizontal">{% csrf_token %}
<input type="button" onclick="start_learn({{course.id}})" value="以我最大的努力去学习这门课程">
</form>
</div>
<table class="table table-hover" style="margin-top:10px">
<tr>
<td>序号</td>
<td>内容标题</td>
<td>概要</td>
<td>发布日期</td>
</tr>
{% for lesson in course.lesson.all %}
<tr id={{ forloop.counter }}>
<td>{{ forloop.counter }}</td>
<td><a href="{% url 'course:detail_lesson' lesson.id %}">{{ lesson.title }}</a></td>
<td>{{ lesson.description | slice:'70'|linebreaks }}</td>
<td>{{ lesson.created|date:"Y-m-d" }}</td>
</tr>
{% empty %}
<p>还没有发布具体内容,请等待。</p>
{% endfor %}
</table>
</div>
<script src='{% static "js/jquery.js" %}'></script>
<script src='{% static "js/csrf.js" %}'></script>
<script>
function start_learn(course_id){
$.ajaxSetup({
beforeSend: function(xhr, settings) {
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]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
$.ajax({
type: "POST",
url: "{% url 'course:lessons_list' course.id %}",
data: {'course_id':course_id},
success:function(e){
if(e=="ok"){
alert("你已经成功注册这门课程")
}else{
alert("对不起,存在一些问题")
}
},
});
}
</script>
{% endblock %}
四 测试
1 浏览器输入:http://localhost:8000/course/lessons-list/8/
2 点击按钮
弹出添加成功按钮
3 查看数据库