Python学习笔记:7.4.3 Django快速建站 - 完善课程管理功能

本文是关于Django快速建站的学习笔记,详细介绍了如何创建和删除课程,包括用户登录验证、发布课程内容的表单处理及删除课程的实现。通过实操演示了如何使用CreateView和DeleteView,以及处理ajax请求。
摘要由CSDN通过智能技术生成

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

一、课程目标
  • 创建课程
  • 删除课程
二、详情解读
2.1.判断用户是否登录

上节课的问题:因为是登录用户才可以访问的,未登录用户访问课程列表,会报错:
在这里插入图片描述

2.1.1.用户登录
  • 安装第三方包:
pip install django-braces
  • 修改views.py,在类视图中继承
from braces.views import LoginRequiredMixin

实操一:
安装好django-braces后,修改myproject/course/views.py

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


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


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

# 多重继承
class UserCourseMixin(UserMixin, LoginRequiredMixin):
    model = Course
    login_url = '/account/login/'  #new

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

说明:
1).引入LoginRequiredMixin
2).UserCourseMixin添加多重继承,并设置参数登录路由login_url

运行结果:(未登录用户访问课程地址时,重定向到登录页面,地址中有next参数,说明登录后页面会跳转到next后的路由中)
在这里插入图片描述

2.2.发布课程内容
2.2.1.功能
  • 填写课程标题
  • 填写课程介绍
  • 点击按钮发布
2.2.2.开发流程
  • 编写表单类:title、overview
  • 类视图
    get请求,呈现表单
    post请求,保存内容

实操二:

Step1:编写表单类。新建文件myproject/course/forms.py

from django import forms
from .models import Course

class CourseCreateForm(forms.ModelForm):
    class Meta:
        model = Course
        fields = ('title', 'overview')

Step2:编写类视图,修改文件myproject/course/views.py

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

# new
from django.views.generic.edit import CreateView
from django.shortcuts import redirect # 实现路由转向
from .forms import CourseCreateForm

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


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

class UserCourseMixin(UserMixin, LoginRequiredMixin):
    model = Course
    login_url = '/account/login/'

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

# new
class CourseCreateView(UserCourseMixin, CreateView):
    fields = ['title', 'overview']
    template_name = 'course/course_create.html'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值