from django.shortcuts import render
from django.views.generic.base import View
from pure_pagination import Paginator, PageNotAnInteger
from .models import Course
from django.http import HttpResponse,JsonResponse
# Create your views here.
class CourseListView(View):
def get(self,request):
all_courses = Course.objects.all().order_by("-add_time")
hot_courses =Course.objects.all().order_by("-click_nums")[:3]
#排序
sort = request.GET.get('sort',"")
if sort:
if sort == "hot":
all_courses = Course.objects.order_by("-click_nums")
elif sort == "students":
all_courses = Course.objects.order_by("-students")
#对课程进行分页
try:
page = request.GET.get('page', 1)
except PageNotAnInteger:
page = 1
p = Paginator(all_courses, 3, request=request)
courses = p.page(page)
return render(request,'course-list.html',{
"all_courses":courses,
"sort":sort,
"hot_courses":hot_courses
})
class CourseDetailView(View):
#课程详情页
def get(self,request,course_id):
course = Course.objects.get(id=int(course_id))
course.click_nums +=1
course.save()
return render(request,'course-detail.html',{
"course":course,
})
这是代码
# -*- coding: utf-8 -*-
from django.conf.urls import url,include
from django.urls import path
from django.views.generic import TemplateView
from .views import CourseListView,CourseDetailView
app_name = 'courses'
urlpatterns = [
# 课程列表页
path('list/',CourseListView.as_view(),name="course_list"),
# 课程详情页
path('detail/<int:course_id>',CourseDetailView.as_view(),name="course_detail"),
]