Django+Xadmin打造在线教育系统(六)
讲师相关功能实现
拷贝并修改teacher-list.html
和teacher-detail.html
,
继承base模板
# 讲师列表
path('teacher_list/', TeacherListView.as_view(), name="teacher_list"),
添加讲师的年龄字段
age = models.IntegerField(default=18, verbose_name=u"年龄")
分页仿照org_list
, 注意__object_list
__
# 课程讲师列表页
class TeacherListView(View):
def get(self, request):
all_teacher = Teacher.objects.all()
# 总共有多少老师使用count进行统计
teacher_nums = all_teacher.count()
# 对讲师进行分页
# 尝试获取前台get请求传递过来的page参数
# 如果是不合法的配置参数默认返回第一页
try:
page = request.GET.get('page', 1)
except PageNotAnInteger:
page = 1
# 这里指从allorg中取五个出来,每页显示5个
p = Paginator(all_teacher, 4, request=request)
teachers = p.page(page)
return render(request, "teachers-list.html", {
"all_teacher":teachers,
"teacher_nums":teacher_nums
})
排序 & 讲师排行榜
sort = request.GET.get("sort", "")
if sort:
if sort == "hot":
all_teacher = all_teacher.order_by("-click_nums")
将sort return到前端。实现active
排行榜讲师
# 排行榜讲师
rank_teacher = Teacher.objects.all().order_by("-fav_nums")[:5]
完善前端代码
讲师详情页
# 访问机构讲师
re_path('teacher/detail/(?P<teacher_id>\d+)/', TeacherDetailView.as_view(), name="teacher_detail"),
# 教师详情页面
class TeacherDetailView(View):
def get(self, request, teacher_id):
teacher = Teacher.objects.get(id = int(teacher_id))
all_course = teacher.course_set.all()
# 排行榜讲师
rank_teacher = Teacher.objects.all().order_by("-fav_nums")[:5]
has_fav_teacher = False
if UserFavorite.objects.filter(user=request.user, fav_type=3, fav_id= teacher.id):
has_fav_teacher = True
has_fav_org = False
if UserFavorite.objects.filter(user=request.user, fav_type=2, fav_id= teacher.org.id):
has_fav_org = True
return render(request, "teacher-detail.html", {
"teacher":teacher,
"all_course":all_course,
"rank_teacher":rank_teacher,
"has_fav_teacher":has_fav_teacher,
"has_fav_org":has_fav_org,
})
收藏功能
# 教师收藏和机构收藏
has_teacher_faved = False
if UserFavorite.objects.filter(user=request.user, fav_type=3, fav_id=teacher.id):
has_teacher_faved = True
has_org_faved = False
if UserFavorite.objects.filter(user=request.user, fav_type=2, fav_id=teacher.org.id):
has_org_faved = True
{% if has_teacher_faved %}已收藏{% else %}收藏{% endif %}
<a class="btn" id="jsRightBtn">{% if has_org_faved %}已收藏{% else %}收藏{% endif %}</a>
Ajax代码参考之前的