django框架的路由
django2 路由支持正则匹配,如:
re_path(r'^category/(?P<category_id>\d+)/$',CourseCategoryView.as_view(),name="course_category"),
视图函数需要接收一个category_id的参数如:
class CourseCategoryView(View):
"""课程类别"""
def get(self,request,category_id):
pass
不然会报错,name的作用:后端可以通过reverse()动态生成url,使用如下:
from django.urls import reverse class CourseCategoryView(View):
"""课程类别"""
def get(self,request,category_id):
course = Course.objects.filter(category=category_id).order_by("-fav_nums")
try:
cur_page = request.GET.get('num', 1)
except Exception as e:
cur_page = 1
page = Pagination(cur_page, course.count())
category = Category.objects.all()
if course:
url = reverse('course:course_category',kwargs={'category_id':category_id})
temp = '<a href="{0}" class="active">{1}</a>'.format(url, course[0].category.name)
page_str = page.get_page_str(url)
return render(request,"course/course-category.html",
{"course_list":course[page.start:page.end_count],
"page_str": page_str,
"category_list": category,
"temp": mark_safe(temp)
})
else:
return redirect(reverse('course:course_list'))
前端使用如下:
{% load staticfiles %}
<a href="{% url 'course:course_category' category_id %}">计算机</a>
pip2 --default-timeout=100 install -U Pillow