Python学习笔记:7.4.2 Django快速建站 - 初步了解Mixin

前言:本文是学习网易微专业的《python全栈工程师 - Django快速建站》课程的笔记,欢迎学习交流。同时感谢老师们的精彩传授!

一、课程目标
  • 增加课程列表功能
  • 初步了解Mixin
二、详情解读
2.1.增加课程列表
2.1.1.需求和实现
  • 用户发布的课程列表
  • 实现:
    – 创建课程模型
    – 迁移数据
    – 类视图:继承通过视图:ListView
    – 模板
    – URL

实操一:

Step1: 创建课程模型。编辑文件myproject/course/models.py

from django.db import models
from django.contrib.auth.models import User


class Course(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='course_user')
    title = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    overview = models.TextField()

    class Meta:
        """
         内部类设置排序字段,以创建时间的倒序排序
        """
        ordering = ('-created',)

    def __str__(self):
        return self.title

Step2:迁移数据

# 记得是在激活的虚拟环境下运行这些命令:
python3 manage.py makemigrations course
python3 manage.py migrate

查看数据库,会发现多了数据表course_course
在这里插入图片描述
Step3:新增类视图,继承通过视图:ListView
编辑文件myproject/course/views.py

from django.shortcuts import render
from django.views.generic import TemplateView, ListView # new
from .models import Course # new

class CourseHome(TemplateView):
    template_name = 'course/home.html'

# new
class CourseListView(ListView):
    model = Course   # 等价于这句 Course.objects.all()
    context_object_name = 'courses'
    template_name = 'course/course_list.html'

说明:
1).引入ListViewCourse模型。
2).类视图必须继承通用视图ListView

Step4:新建模板文件myproject/templates/course/course_list.html

{% extends 'base.html' %}
{% block title %}Course List{% endblock %}

{% block content %}
<div class="container">
    <table class="table table-hover">
        <tr>
            <td>序号</td>
            <td>标题</td>
            <td>讲师</td>
            <td>日期</td>
        </tr>
        {% for course in courses %}
            <tr id={{ forloop.counter }}>
                <td>{{ forloop.counter }}</td>
                <td>{{ course.title }}</td>
                <td>{{ course.user.username }}</td>
                <td>{{ course.created }}</td>
            </tr>
        {% endfor %}
    </table>
</div>
{% endblock %}

说明:
1).{{ forloop.counter }}获取循环的顺序索引
step5:配置URL,修改文件myproject/course/urls.py

# -*- coding=utf-8 -*-
from django.urls import path
# from django.views.generic import TemplateView
from .views import CourseHome, CourseListView #new

app_name = 'course'

urlpatterns = [
	# path('', TemplateView.as_view(template_name='course/home.html')),
	path('', CourseHome.as_view()),
	path('course-list/', CourseListView.as_view(), name='course_list'), #new
]

访问地址http://127.0.0.1:8000/course/course-list/,运行结果:(以下数据是手动在数据库直接添加的,“创建课程”的内容下节课会学习到)

在这里插入图片描述

2.2.Mixin
  • 不是“迷信”
  • Mix-in:原指一种冰激凌和另外一种风味的甜食混合而成的事件。mix来自mixture

实操二: 只显示登录用户发布的课程

Step1:修改文件myproject/course/views.py

from django.shortcuts import render
from django.views.generic import TemplateView, ListView
from .models import Course 

class CourseHome(TemplateView):
    template_name = 'course/home.html'

# new
class UserMixin:
    def get_queryset(self):
        qs = super(UserMixin, self).get_queryset()
        return qs.filter(user=self.request.user)

# new
class UserCourseMixin(UserMixin):
    model = Course

class CourseListView(UserCourseMixin, ListView):
    # model = Course
    context_object_name = 'courses'
    template_name = 'course/course_list.html'

说明:
0).重写通用视图中的get_queryset()方法,返回当前登录用户的数据。
1).新增类UserMixinUserCourseMixin。此处它们不是类视图,所以类名后缀用Mixin标记。
2).get_queryset()作用是筛选用户。
3).类UserCourseMixin继承了类UserMixin
4).CourseListView继承了UserCourseMixin,因此它原先的model = Course可以注释掉。
5).注意:此处CourseListView中是多重继承。通常情况下Mixin相关的继承放左边,其他的放右边。
6).《与基于类的视图一起使用 mixins》请参考官网文档

三、课程小结
  • 01 类视图ListView
  • 02 Mixin
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值