您现在的位置是: 网站首页 >Django >Django2.0.8+xadmin2实现在线学习网站 Django

【Django在线教育平台】21.其他功能完善

admin2019年6月4日 14:22 Django | Html | JQuery 1219人已围观

Django2.0.8+xadmin2实现在线学习网站简介 Django2.0.8+xadmin2实现在线学习网站,课程、讲师、机构、用户收藏功能。GitHub地址:https://github.com/xyliurui/OnlineLearningPlatform ;Django版本:2.0.8

# 其他完善 ## 课程、讲师收藏数功能增加 之前只写了用户收藏机构,机构收藏数变化。现在需要将课程、讲师收藏后,收藏数进行变化 ```python # 机构收藏或取消收藏 class AddFavView(View): # (1, "课程"), # (2, "课程机构"), # (3, "讲师") def post(self, request): # 收藏的不管是课程,讲师,还是机构,都是记录他们的id,如果没取到把它设置未0,避免查询时异常 fav_id = request.POST.get('fav_id', 0) # 表明收藏的类别 fav_type = request.POST.get('fav_type', 0) # 收藏与已收藏取消收藏 # 判断用户是否登录:即使没登录会有一个匿名的user if not request.user.is_authenticated: # 未登录时返回json提示未登录,跳转到登录页面是在ajax中做的 return HttpResponse('{"fav_status":"fail", "fav_msg":"用户未登录"}', content_type='application/json') exist_records = UserFavorite.objects.filter(user=request.user, fav_id=fav_id, fav_type=fav_type) if exist_records: # 如果已经存在,表明用户取消收藏 exist_records.delete() if int(fav_type) == 2: # 机构模型中存储的收藏数减1 CourseOrg.objects.get(id=fav_id).change_fav_nums(add=-1) elif int(fav_type) == 1: # 课程收藏-1 course = Course.objects.get(id=fav_type) course.fav_nums -= 1 if course.fav_nums < 0: course.fav_nums = 0 # 避免负数出现 course.save(update_fields=['fav_nums']) elif int(fav_type) == 3: # 讲师收藏-1 teacher = Teacher.objects.get(id=fav_id) teacher.fav_nums -= 1 if teacher.fav_nums < 0: teacher.fav_nums = 0 # 避免负数出现 teacher.save(update_fields=['fav_nums']) return HttpResponse('{"fav_status":"success", "fav_msg":"添加收藏"}', content_type='application/json') else: user_fav = UserFavorite() # 如果取到了id值才进行收藏 if int(fav_id) > 0 and int(fav_type) > 0: user_fav.fav_id = fav_id user_fav.fav_type = fav_type user_fav.user = request.user user_fav.save() if int(fav_type) == 2: # 机构模型中存储的收藏数加1 CourseOrg.objects.get(id=fav_id).change_fav_nums(add=1) elif int(fav_type) == 1: # 课程收藏-1 course = Course.objects.get(id=fav_type) course.fav_nums += 1 course.save(update_fields=['fav_nums']) elif int(fav_type) == 3: # 讲师收藏-1 teacher = Teacher.objects.get(id=fav_id) teacher.fav_nums += 1 teacher.save(update_fields=['fav_nums']) return HttpResponse('{"fav_status":"success", "fav_msg":"取消收藏"}', content_type='application/json') else: return HttpResponse('{"fav_status":"fail", "fav_msg":"收藏出错"}', content_type='application/json') ``` 修改organization.views.py中的机构数量更改 ```python def change_fav_nums(self, add=1): self.fav_nums += add if self.fav_nums < 0: self.fav_nums = 0 self.save(update_fields=['fav_nums']) ``` ## 消息变为已读 ```python # 用户消息 class MyMessageView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'next' def get(self, request): all_user_msg = UserMessage.objects.all().filter(user=request.user.id) # 当访问我的消息时,所有未读消息变为已读 UserMessage.objects.filter(user=request.user.id, has_read=False).update(has_read=True) # 分页 try: page = request.GET.get('page', 1) except PageNotAnInteger: page = 1 # 这里指从all_course中取8个出来,每页显示8个 p = Paginator(all_user_msg, 8, request=request) all_user_msg = p.page(page) return render(request, 'usercenter-msg.html', locals()) ``` ## 首页轮播图 ### 修改首页url ```python from users.views import IndexView urlpatterns = [ path('admin/', admin.site.urls), path('xadmin/', xadmin.site.urls), # path('', TemplateView.as_view(template_name='index.html'), name='index'), path('', IndexView.as_view(), name='index'), ] ``` ### 课程模型添加是否轮播字段 courses/models.py ```python # 课程信息表 class Course(models.Model): DEGREE_CHOICES = ( ("cj", "初级"), ("zj", "中级"), ("gj", "高级") ) name = models.CharField(max_length=50, verbose_name='课程名') desc = models.CharField(max_length=300, verbose_name='课程描述') # 后面会改为富文本 detail = models.TextField(verbose_name='课程详情') degree = models.CharField(max_length=3, choices=DEGREE_CHOICES, verbose_name='课程难度') learn_times = models.IntegerField(default=0, verbose_name='学习时长(分钟数)') # 点击开始学习后记录学习人数 students = models.IntegerField(default=0, verbose_name='学习人数') fav_nums = models.IntegerField(default=0, verbose_name='收藏人数') image = models.ImageField(upload_to='course/%Y/%m', max_length=100, blank=True, null=True, verbose_name='封面图(160*160px)') # 点击到课程信息界面即需要记录点击数 click_nums = models.IntegerField(default=0, verbose_name='点击数') add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间') course_org = models.ForeignKey(CourseOrg, null=True, blank=True, related_name='courses', on_delete=models.CASCADE, verbose_name='所属机构') category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL, related_name='courses', verbose_name='课程类别') # 课程类别删除后课程该字段设置为null tags = models.ManyToManyField(Tag, related_name='courses', blank=True, verbose_name='课程标签') teacher = models.ForeignKey(Teacher, related_name='courses', null=True, blank=True, on_delete=models.SET_NULL, verbose_name='讲师') notes = models.CharField(max_length=20, default='人生苦短,我用Python!', verbose_name='课程须知') tell_you = models.CharField(max_length=20, default='', verbose_name='讲师告诉你学到了什么') is_banner = models.BooleanField(default=False, verbose_name='是否轮播') class Meta: verbose_name = verbose_name_plural = '课程' def get_lesson_nums(self): # 获取课程章节数,如果章节模型中未定义关联名称(related_name)则直接使用字段名_set来获取 return self.lesson_set.all().count() def __str__(self): return self.name ``` 添加完后执行同步 ### 主页视图 ```python from users.models import Banner class IndexView(View): def get(self, request): all_banner = Banner.objects.all() first_org = CourseOrg.objects.order_by('-students', '-click_nums', '-fav_nums').first() # 最火机构 first_teacher = Teacher.objects.order_by('-fav_nums', '-click_nums').first() # 最强讲师 # 课程位,取4个进行显示 courses = Course.objects.all()[:8] # 轮播图课程位取1个显示 banner_course = Course.objects.filter(is_banner=True).first() # 课程机构 course_orgs = CourseOrg.objects.all() return render(request, 'index.html', locals()) ``` ### 登录返回首页数据空的问题 修改登录视图,将登陆成功返回index.html改为重定向到index ```python # 基于类的视图实现登录 class LoginView(View): def get(self, request): return render(request, 'login.html', {}) def post(self, request): login_form = LoginForm(request.POST) if login_form.is_valid(): user_name = request.POST.get('username', '') pass_word = request.POST.get('password', '') user = authenticate(username=user_name, password=pass_word) # 认证成功返回user对象,失败返回null if user: login(request, user) # return render(request, 'index.html') return HttpResponseRedirect(reverse('index')) else: return render(request, 'login.html', { 'msg': '用户名或密码错误!', 'login_form': login_form, }) else: return render(request, 'login.html', { 'login_form': login_form, }) ``` ![BLOG_20190604_142345_56](/media/blog/images/2019/06/BLOG_20190604_142345_56.png "博客图集BLOG_20190604_142345_56.png") ![BLOG_20190604_142340_50](/media/blog/images/2019/06/BLOG_20190604_142340_50.png "博客图集BLOG_20190604_142340_50.png") ![BLOG_20190604_142335_35](/media/blog/images/2019/06/BLOG_20190604_142335_35.png "博客图集BLOG_20190604_142335_35.png") ## 配置全局404和500 在主urls.py中,增加一个全局变量 ```python # 全局404页面配置 handler404 = 'users.views.page_not_found' # 全局500配置 handler500 = 'users.views.page_error' ``` users/views.py增加处理函数 ```python # 全局404处理函数 def page_not_found(request): from django.shortcuts import render_to_response response = render_to_response('404.html') # 设置response的状态码 response.status_code = 404 return response # 全局500处理函数 def page_error(request): from django.shortcuts import render_to_response response = render_to_response('500.html') # 设置response的状态码 response.status_code = 500 return response ``` `Debug = True` 404是不起作用的,settings.py要处理配置DEBUG为False才能显示错误页面 ```python # DEBUG = True DEBUG = False ALLOWED_HOSTS = ['*'] ``` 在debug为false情况下。 在访问media的时候配置过用serve来取, 告诉它访问media的时候去哪个路径下找 debug为True 会自动前往STATICFILES——DIRS取文件的 一旦debug改为false,django就不会代管你的静态文件, 一般静态文件通过第三方http服务器代理转发。 nignx 和 Apache都会自动代理这些静态文件 url响应static 修改settings.py文件 ```python STATIC_ROOT = os.path.join(BASE_DIR, 'static') ``` **以上没搞好** # 主页模版标签显示用户收藏 ## 创建模版标签 在user应用下创建templatetags包,然后创建名为user_template_tags的py文件 ```python from django import template from operation.models import UserFavorite from courses.models import Course from organization.models import Teacher, CourseOrg register = template.Library() # 只有向系统注册过的tags,系统才认得你 @register.simple_tag def get_user_fav(user): # 获取所有用户收藏的课程 all_user_fav_course = UserFavorite.objects.filter(user=user, fav_type=1) all_fav_course = [Course.objects.get(id=user_fav_course.fav_id) for user_fav_course in all_user_fav_course] # 获取所有用户收藏的讲师 all_user_fav_teacher = UserFavorite.objects.filter(user=user, fav_type=3) all_fav_teacher = [Teacher.objects.get(id=user_fav_teacher.fav_id) for user_fav_teacher in all_user_fav_teacher] # 收藏的机构 all_user_fav_org = UserFavorite.objects.filter(user=user, fav_type=2) all_fav_org = [CourseOrg.objects.get(id=user_fav_org.fav_id) for user_fav_org in all_user_fav_org] return all_fav_course[:3], all_fav_teacher[:3], all_fav_org[:3], len(all_fav_course) + len(all_fav_teacher) + len(all_fav_org) ``` ## 模板base.html中使用模板标签 ```html {% load user_template_tags %} <ul class="nav navbar-right cart-pop"> {% get_user_fav request.user as user_fav %} <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><span class="itm-cont">{{ user_fav.3 }}</span> <i class="flaticon-shopping-bag"></i> <strong>我的收藏</strong> <br> <span></span></a> <ul class="dropdown-menu"> <li>收藏的课程(最多显示3条)</li> {% for course in user_fav.0 %} <li> <div class="media-body"><a href="{% url 'course:course_detail' course.id %}" class="tittle">【{{ course.name }}】&nbsp;&nbsp;&nbsp;<b>{{ course.get_degree_display }}</b></a> </div> </li> {% empty %} <li> <div class="media-body">暂无</div> </li> {% endfor %} <li>收藏的讲师(最多显示3条)</li> {% for teacher in user_fav.1 %} <li> <div class="media-body"><a href="{% url 'teacher:teacher_detail' teacher.id %}" class="tittle">【{{ teacher.name }}】&nbsp;&nbsp;&nbsp;<b>{{ teacher.work_company }}</b></a> </div> </li> {% empty %} <li> <div class="media-body">暂无</div> </li> {% endfor %} <li>收藏的机构(最多显示3条)</li> {% for org in user_fav.2 %} <li> <div class="media-body"><a href="{% url 'org:org_home' org.id %}" class="tittle">【{{ org.name }}】&nbsp;&nbsp;&nbsp;<b>{{ org.course_nums }} 个课程</b></a> </div> </li> {% empty %} <li> <div class="media-body">暂无</div> </li> {% endfor %} <li class="btn-cart"><a href="{% url 'usercenter:my_favorite' %}" class="btn-round">我的收藏</a></li> </ul> </li> </ul> ``` ![BLOG_20190604_142313_25](/media/blog/images/2019/06/BLOG_20190604_142313_25.png "博客图集BLOG_20190604_142313_25.png")

很赞哦! (0)

文章交流

  • emoji
0人参与,0条评论

当前用户

未登录,点击   登录

站点信息

  • 建站时间:网站已运行2285天
  • 系统信息:Linux
  • 后台程序:Python: 3.8.10
  • 网站框架:Django: 3.2.6
  • 文章统计:257 篇
  • 文章评论:63 条
  • 腾讯分析网站概况-腾讯分析
  • 百度统计网站概况-百度统计
  • 公众号:微信扫描二维码,关注我们
  • QQ群:QQ加群,下载网站的学习源码
返回
顶部
标题 换行 登录
网站