学一学书里的django是怎么写views.py的

他山之石,可以攻玉嘛。

好的习惯有时也是学别人来养成的。

外国人的编码习惯,学啊。

from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect, get_object_or_404
from django.forms.models import modelform_factory
from django.apps import apps
from django.views.generic.base import TemplateResponseMixin, View
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from braces.views import LoginRequiredMixin, PermissionRequiredMixin
from braces.views import CsrfExemptMixin, JsonRequestResponseMixin
from .models import Course, Module, Content
from .forms import ModuleFormSet
from django.db.models import Count
from .models import Subject
from django.views.generic.detail import DetailView
from students.forms import CourseEnrollForm
# Create your views here.

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

class OwnerEditMixin(object):
    def form_valid(self, form):
        form.instance.owner = self.request.user
        return super(OwnerEditMixin, self).form_valid(form)

class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin):
    model = Course
    fields = [‘subject‘, ‘title‘, ‘slug‘, ‘overview‘]
    success_url = reverse_lazy(‘manage_course_list‘)

class OwnerCourseEditMinxin(OwnerCourseMixin, OwnerEditMixin):
    fields = [‘subject‘, ‘title‘, ‘slug‘, ‘overview‘]
    success_url = reverse_lazy(‘manage_course_list‘)
    template_name = ‘courses/manage/course/form.html‘

class ManageCourseListView(OwnerCourseMixin, ListView):

    template_name = ‘courses/manage/course/list.html‘

class CourseCreateView(PermissionRequiredMixin,
                       OwnerCourseEditMinxin,
                       CreateView):
    permission_required = ‘courses.add_course‘

class CourseUpdateView(PermissionRequiredMixin,
                       OwnerCourseEditMinxin,
                       UpdateView):
    permission_required = ‘courses.change_course‘

class CourseDeleteView(PermissionRequiredMixin,
                       OwnerCourseMixin,
                       DeleteView):
    template_name = ‘courses/manage/course/delete.html‘
    success_url = reverse_lazy(‘manage_course_list‘)
    permission_required = ‘courses.delete_course‘

class CourseModuleUpdateView(TemplateResponseMixin, View):
    template_name = ‘courses/manage/module/formset.html‘
    course = None

    def get_formset(self, data=None):
        return ModuleFormSet(instance=self.course,
                             data=data)

    def dispatch(self, request, pk):
        self.course = get_object_or_404(Course, id=pk, owner=request.user)
        return super(CourseModuleUpdateView, self).dispatch(request, pk)

    def get(self, request, *args, **kwargs):
        formset = self.get_formset()
        return self.render_to_response({‘course‘: self.course,
                                        ‘formset‘: formset})

    def post(self, request, *args, **kwargs):
        formset = self.get_formset(data=request.POST)
        if formset.is_valid():
            formset.save()
            return redirect(‘manage_course_list‘)
        return self.render_to_response({‘course‘: self.course,
                                        ‘formset‘: formset})

class ContentCreateUpdateView(TemplateResponseMixin, View):
    module = None
    model = None
    obj = None
    template_name = ‘courses/manage/content/form.html‘

    def get_model(self, model_name):
        if model_name in [‘text‘, ‘video‘, ‘image‘, ‘file‘]:
            return apps.get_model(app_label=‘courses‘,
                                  model_name=model_name)
        return None

    def get_form(self, model, *args, **kwargs):
        Form = modelform_factory(model, exclude=[‘owner‘,
                                                 ‘order‘,
                                                 ‘created‘,
                                                 ‘updated‘])
        return Form(*args, **kwargs)

    def dispatch(self, request, module_id, model_name, id=None):
        self.module = get_object_or_404(Module,
                                        id=module_id,
                                        course__owner=request.user)
        self.model = self.get_model(model_name)
        if id:
            self.obj = get_object_or_404(self.model, id=id, owner=request.user)
        return super(ContentCreateUpdateView, self).dispatch(request, module_id, model_name, id)

    def get(self, request, module_id, model_name, id=None):
        form = self.get_form(self.model, instance=self.obj)
        return self.render_to_response({‘form‘: form, ‘object‘: self.obj})

    def post(self, request, module_id, model_name, id=None):
        form = self.get_form(self.model,
                             instance=self.obj,
                             data=request.POST,
                             files=request.FILES)
        if form.is_valid():

            obj = form.save(commit=False)
            obj.owner = request.user
            obj.save()
            print id, ‘&&&&&&&&&&&‘
            if not id:
                print ‘****************‘
                Content.objects.create(module=self.module,
                                       item=obj)
                print ‘****************‘
            return redirect(‘module_content_list‘, self.module.id)
        return self.render_to_response({‘form‘: form, ‘object‘: self.obj})

class ContentDeleteView(View):
    def post(self, request, id):
        content = get_object_or_404(Content,
                                    id=id,
                                    module__course__owner=request.user)
        module = content.module
        content.item.delete()
        content.delete()
        return redirect(‘module_content_list‘, module.id)

class ModuleContentListView(TemplateResponseMixin, View):
    template_name = ‘courses/manage/module/content_list.html‘

    def get(self, request, module_id):
        module = get_object_or_404(Module,
                                   id=module_id,
                                   course__owner=request.user)
        return self.render_to_response({‘module‘: module})

class ModuleOrderView(CsrfExemptMixin,
                      JsonRequestResponseMixin,
                      View):
    def post(self, request):
        for id, order in self.request_json.items():
            Module.objects.filter(id=id,
                                  course__owner=request.user).update(order=order)
        return self.render_json_response({‘saved‘: ‘OK‘})

class ContentOrderView(CsrfExemptMixin,
                       JsonRequestResponseMixin,
                       View):
    def post(self, request):
        for id, order in self.request_json.items():
            Content.objects.filter(id=id,
                                   module__course__owner=request.user)                .update(order=order)
        return self.render_json_response({‘saved‘: ‘OK‘})

class CourseListView(TemplateResponseMixin, View):
    model = Course
    template_name = ‘courses/course/list.html‘

    def get(self, request, subject=None):
        subjects = Subject.objects.annotate(
            total_courses=Count(‘courses‘)
        )
        courses = Course.objects.annotate(
            total_modules=Count(‘modules‘)
        )
        if subject:
            subject = get_object_or_404(Subject, slug=subject)
            courses = courses.filter(subject=subject)
        print ‘***********‘, subjects, courses, subject
        return self.render_to_response({‘subjets‘: subjects,
                                        ‘subject‘: subject,
                                        ‘courses‘: courses})

class CourseDetailView(DetailView):
    model = Course
    template_name = ‘courses/course/detail.html‘

    def get_context_data(self, **kwargs):
        context = super(CourseDetailView,
                        self).get_context_data(**kwargs)
        context[‘enroll_form‘] = CourseEnrollForm(
            initial={‘course‘: self.object})
        return context
时间: 2024-10-04 17:41:42

学一学书里的django是怎么写views.py的的相关文章

Django视图层(views.py)

视图函数 接受Web请求并且返回Web响应.由此,视图函数应该接收请求对象HttpRequest,并返回响应对象HttpResponse. request django将请求报文中的请求行.首部信息.内容主体封装成 HttpRequest 类中的属性. request.scheme # 请求的协议,一般为http或者https,字符串格式(以下属性中若无特殊指明,均为字符串格式)request.body   #http请求的主体,二进制格式.request.path        # 所请求页面

Django之视图(views.py)

1,视图的作用就是URL和模板的连接器,我们在浏览器中输入URL,Django通过视图找到相应的模板,然后返回给浏览器. 2,视图的URL配置过程:setting中的:ROOT_URLCONF,然后是项目中的url.py的配置,然后是APP中的url.py的配置 setting: ROOT_URLCONF = 'lianxi03.urls' 项目url: from django.contrib import admin from django.urls import path,include u

django之视图系统 views.py

一个视图函数(类),简称视图,是一个简单的Python 函数(类),它接受Web请求并且返回Web响应. 视图的实现可以基于两种方法: 1 基于函数的形式 FBV 2 基于类的方式实现 原文地址:https://www.cnblogs.com/mmyy-blog/p/9826001.html

[py][mx]django使用class写views-免去判断方法的烦恼

修改views使用class模式 类模式写views - 免去了函数模式的判断的烦恼 users/views.py from django.views.generic import View class UserView(View):#继承了View类,它里面实现get post等方法, 使用类模式写免去了函数模式的判断 def get(self, request): return render(request, "login.html", {}) def post(self, req

[Django笔记] views.py 深入学习

views.py 是django MTV 中的主要逻辑层,相当于MVC中的 Controller 以下的实例都基于这样一个路由表: urlpatterns = [ url(r'^(index)?$', views.index, name='index'), url(r'^posts/$', views.PostsView.as_view(), name='posts'), url(r'^article/(?P<aid>[0-9]+)/$', views.ArticleView.as_view(

Django基础之视图层(views.py)和模板层

目录 Django基础之视图层(views.py)和模板层 视图层 JsonResponse对象 form表单上传文件 FBV与CBV 即CBV源码分析 django settings源码分析及实际应用 模板层 模板传值 过滤器( | ) 常用内置过滤器 其他过滤器(了解) 标签 if判断 for循环 with标签 csrf_token标签 自定义过滤器和标签 自定义过滤器 自定义标签 自定义过滤器和标签的区别 模板的继承 模板的导入 Django基础之视图层(views.py)和模板层 视图层

Django 1.6 最佳实践: 如何设置django项目的设置(settings.py)和部署文件(requirements.txt)

Django 1.6 最佳实践: 如何设置django项目的设置(settings.py)和部署文件(requirements.txt) 作者: Desmond Chen,发布日期: 2014-05-17, 修改日期: 2014-05-18 在Django 1.6中的settings.py中可以修改130多项设置, 但大多数都继承自默认值. 设置是在web服务器启动时首次载入的, 服务器重启时重新载入, 因此, 程序员们应尽量避免修改正式服务器上使用的settings.py文件. 以下是一些我们

从零开始学ios开发(十二):Table Views(中)UITableViewCell定制

我们继续学习Table View的内容,这次主要是针对UITableViewCell,在前一篇的例子中我们已经使用过UITableViewCell,一个默认的UITableViewCell包含imageView.textLabel.detailTextLabel等属性,但是很多时候这些默认的属性并不能满足需要,其实更多的时候我们想自己制定UITableViewCell的内容,这篇学习的就是制定自己的UITableViewCell. UITableViewCell继承自UIView,因此它可以加载

【Django】如何自定义manage.py命令? 达到启动后台进程的目的?

代码: #-*- coding:utf-8 -*- """ The handle active user mail send """ from django.core.management.base import BaseCommand, CommandError from django.db import models #from placeholders import * import os import time import loggin