web应用框架——Django实践项目(六)

2020-05-17  本文已影响0人  思君_4cd3

一.课程机构模块

from apps.organization.models import CourseOrg
...
course_org = models.ForeignKey(CourseOrg, null=True, blank=True, on_delete=models.CASCADE, verbose_name="课程机构")
makemigrations
migrate

二.公开课分页模块

                     {% if all_courses.has_previous %}
                                <li class="long"><a href="?{{ all_courses.previous_page_number.querystring }}"
                                                    class="page">上一页</a></li>
                            {% endif %}
                            {% for page in all_courses.pages %}
                                {% if page %}
                                    {% ifequal page all_courses.number %}
                                        <li class="active"><a
                                                href="?{{ page.querystring }}">{{ page }}</a>
                                        </li>
                                    {% else %}
                                        <li class="page"><a
                                                href="?{{ page.querystring }}">{{ page }}</a>
                                        </li>
                                    {% endifequal %}
                                {% else %}
                                    <li class="none">...</li>
                                {% endif %}
                            {% endfor %}
                            {% if all_courses.has_next %}
                                <li class="long"><a href="?{{ all_courses.next_page_number.querystring }}"
                                                    class="page">下一页</a></li>
                            {% endif %}

三.课程排序

        #课程排序
        sort = request.GET.get('sort', "")
        if sort == 'students':
            # 根据参与人数排序  减号代表倒序排序的意思
            # li><a href="?sort=students">参与人数</a></li>
            all_courses = all_courses.order_by('-students')
        elif sort == 'hot':
            # 课程排序  <li><a href="?sort=hot">最热门</a></li>
            # 根据最热门进行排序 参与人数  <
            all_courses = all_courses.order_by('-click_nums')
...
"sort":sort,
<li class="{% if sort == '' %}active{% endif %}"><a href="?sort=">最新 </a></li>
                            <li class="{% if sort == 'hot' %}active{% endif %}"><a href="?sort=hot">最热门</a></li>
                            <li class="{% if sort == 'students' %}active{% endif %}"><a href="?sort=students">参与人数</a></li>

四.课程热门推荐

## 获取热门课程 前3个
        hot_courses = Course.objects.order_by("-click_nums")[:3]
...
"hot_courses":hot_courses,
{% for course in hot_courses %}
                        <dl>
                            <dt>
                                <a target="_blank" href="">
                                    <img width="240" height="220" class="scrollLoading"
                                         src="{{ course.image.url }}"/>
                                </a>
                            </dt>
                            <dd>
                                <a target="_blank" href=""><h2>{{ course.name }}</h2></a>
                                <span class="fl">难度:<i class="key">{{course.get_degree_display}}</i></span>
                            </dd>
                        </dl>
                        {% endfor %}

五.导航栏样式修改

<ul>
                            <li class="{% if request.path == '/' %}active{% endif %}"><a href="{% url 'index' %}">首页</a></li>
                            <li class="{% if request.path|slice:'7' == '/course' %}active{% endif %}">
                                <a href="{% url 'course:list' %}">
                                    公开课<img class="hot" src="/static/images/nav_hot.png">
                                </a>
                            </li>
                            <li>
                                <a href="teachers-list.html">授课教师</a>
                            </li>
                            <li class="{% if request.path|slice:'4' == '/org' %}active{% endif %}"><a href="{% url 'org:list' %}">授课机构</a></li>
                        </ul>

六.课程详细页

课程详细页面链接:https://pan.baidu.com/s/1NFpVJHojbLI876ieXOlAVA
提取码:m077

from apps.courses.views import CourseListView,CourseDetailView
...
url(r'^detail/$', CourseDetailView.as_view(), name='detail'),
class CourseDetailView(View):
    def get(self, request, *args, **kwargs):
        """获取课程详情页"""
        return render(request, 'course-detail.html')

七.详情页和公开课关联:

class CourseDetailView(View):
    def get(self, request,course_id, *args, **kwargs):
        """获取课程详情页"""
        # 根据id查询课程
        course = Course.objects.get(id=int(course_id))
        # 点击到课程 的详情就记录一次点击数
        course.click_nums += 1
        course.save()

        return render(request, 'course-detail.html',
                      {"course":course,
                       })
url(r'^(?P<course_id>\d+)/$', CourseDetailView.as_view(), name='detail'),

八.详情页面包屑模块:

<section>
<div class="wp">
    <ul class="crumbs">

        <li><a href="{% url 'index' %}">首页</a>></li>
        <li><a href="{% url 'course:list' %}">公开课</a>></li>
         <li>课程详情</li>

    </ul>
</div>
</section>

九.细节完善

1.图片:

2.细节

3.章节数

    def lesson_nums(self):
        #章节数
        return self.lesson_set.all().count()

十.收藏状态

from apps.operations.models import UserFavorite
...
# 获取收藏状态
        has_fav_course = False
        has_fav_org = False
        if request.user.is_authenticated:
            # 查询用户是否收藏了该课程和机构 fav_type=1证明是课程收藏,如果有,证明用户收藏了这个课
            if UserFavorite.objects.filter(user=request.user, fav_id=course.id, fav_type=1):
                has_fav_course = True
            if UserFavorite.objects.filter(user=request.user, fav_id=course.id, fav_type=2):
                has_fav_org = True
...
"has_fav_course": has_fav_course,
                       "has_fav_org": has_fav_org,
{% if has_fav_course %}已收藏{% else %}收藏{% endif %}
...
{% if has_fav_org %}已收藏{% else %}收藏{% endif %}

十一.课程收藏和机构收藏的实现

{% block custom_js %}
<script>

    function add_fav(current_elem, fav_id, fav_type) {
        $.ajax({
            cache: false,
            type: 'POST',
            url: '{% url 'op:fav' %}',
            async: true,
            data: {'fav_id':fav_id,'fav_type':fav_type },
            beforeSend: function(xhr, settings){
                xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
            },
            success: function (data) {
                if (data.status == 'fail'){
                    if (data.msg == '用户未登录'){
                        window.location.href = '{% url 'login' %}'
                    }else {
                        alert(data.msg)
                    }
                }else if(data.status == 'success'){
                    current_elem.text(data.msg)
                }
            }
                })
    }
    {#课程收藏的实现#}
    $(document).ready(function () {
        $('#jsLeftBtn').on('click', function () {
            add_fav($(this), {{ course.id }}, 1)
        })
    })

    {#机构收藏的实现#}
    $(document).ready(function () {
        $('#jsRightBtn').on('click', function () {
             add_fav($(this), {{ course.course_org.id }}, 2)
        })
    })
</script>
{% endblock %}
from django.conf.urls import url

from apps.operations.views import AddFavView

urlpatterns = [
    url(r'^fav/$', AddFavView.as_view(), name='fav'),
]
# 用户操作相关
    url(r'^op/', include(('apps.operations.urls', 'operations'), namespace='op')),
from apps.operations.models import UserFavorite
from django import forms
class UserFavForm(forms.ModelForm):
    class Meta:
        model = UserFavorite
        fields = ["fav_id","fav_type"]
from django.shortcuts import render
from django.views.generic.base import View
from apps.operations.forms import UserFavForm
from django.http import JsonResponse
from apps.operations.models import UserFavorite
from apps.courses.models import Course
from apps.organization.models import CourseOrg
from apps.organization.models import Teacher
class AddFavView(View):
    """
    用户收藏实现
    """
    # 先判断用户是否登录
    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return JsonResponse({
                "status":"fail",
                "msg": "用户未登录"
            })
        use_fav_form = UserFavForm(request.POST)
        if use_fav_form.is_valid():
            fav_id = use_fav_form.cleaned_data["fav_id"]
            fav_type = use_fav_form.cleaned_data["fav_type"]
            # 判断用户是否已经收藏
            existed_records = UserFavorite.objects.filter(user=request.user,fav_id=fav_id,fav_type=fav_type )
            if existed_records:
                # 收藏这条信息删除
                existed_records.delete()
                if fav_type == 1:
                    course = Course.objects.get(id = fav_id)
                    course.fav_nums -= 1
                    course.save()
                elif fav_type == 2:
                    cousre_org = CourseOrg.objects.get(id=fav_id)
                    cousre_org.fav_nums -= 1

                elif fav_type == 3:
                    teacher =Teacher.objects.get(id=fav_id)
                    teacher.fav_nums -= 1
                    teacher.save()
                return JsonResponse(
                    { "status":"success",
                    "msg": "收藏"}
                )
            else:
                user_fav = UserFavorite()
                user_fav.fav_id = fav_id
                user_fav.fav_type = fav_type
                user_fav.user = request.user
                user_fav.save()
                return JsonResponse(
                    {"status": "success",
                     "msg": "已收藏"}
                )

        else:
            return JsonResponse(
                {"status": "fail",
                 "msg": "参数错误"}
            )

以上代码可以在GitHub上查看:

https://github.com/zhaoXiY/MXOline

(此文章仅作为个人学习笔记使用,如有错误欢迎指正~)

上一篇 下一篇

猜你喜欢

热点阅读