他山之石,可以攻玉嘛。

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

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

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

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

  1. django搭建web (五) views.py

    http请求: HttpRequest http响应: HttpResponse 所在位置:django.http isinstance(request,HttpResponse) True-> ...

  2. pycharm 里运行 django 工程 You must either define the environment variable DJANGO_SETTINGS_MODULE 错误

    pycharm 里运行 django 工程出现错误(在命令行直接运行ok): django.core.exceptions.ImproperlyConfigured: Requested settin ...

  3. 小白学Python | 最简单的Django 简明教程

    作者:浅雨凉 来源:http://www.cnblogs.com/qianyuliang/p/6814376.html 一.Django简介 1. web框架介绍 具体介绍Django之前,必须先介绍 ...

  4. ORM基础3 在python脚本里调用Django环境

    1.查询 1.# all获取所有的object,结果QuerySet,列表 print('all'.center(80, '=')) ret = models.Person.objects.all() ...

  5. [大数据从入门到放弃系列教程]在IDEA的Java项目里,配置并加入Scala,写出并运行scala的hello world

    [大数据从入门到放弃系列教程]在IDEA的Java项目里,配置并加入Scala,写出并运行scala的hello world 原文链接:http://www.cnblogs.com/blog5277/ ...

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

    修改views使用class模式 类模式写views - 免去了函数模式的判断的烦恼 users/views.py from django.views.generic import View clas ...

  7. 第三百零四节,Django框架,urls.py模块,views.py模块,路由映射与路由分发以及逻辑处理——url控制器

    Django框架,urls.py模块,views.py模块,路由映射与路由分发以及逻辑处理——url控制器 这一节主讲url控制器 一.urls.py模块 这个模块是配置路由映射的模块,当用户访问一个 ...

  8. Django框架_URLconf、Views、template、ORM

    目录: 一.Django-MTV MTV模型 Django基本命令 视图层之路由配置系统(views) 视图层之视图函数(views) 模板层(template) 二.Django-model基础 O ...

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

    views.py 是django MTV 中的主要逻辑层,相当于MVC中的 Controller 以下的实例都基于这样一个路由表: urlpatterns = [ url(r'^(index)?$', ...

随机推荐

  1. [Usaco2018 Open]Milking Order

    Description Farmer John的N头奶牛(1≤N≤10^5),仍然编号为1-N,正好闲得发慌.因此,她们发展了一个与Farmer John每天早上为她们挤牛奶的时候的排队顺序相关的复杂 ...

  2. HDU 4691 后缀数组+RMQ

    思路: 求一发后缀数组,求个LCP 就好了 注意数字有可能不只一位 (样例2) //By SiriusRen #include <bits/stdc++.h> using namespac ...

  3. [转]MySQL存储过程

    转自:http://www.cnblogs.com/exmyth/p/3303470.html 14.1.1 创建存储过程 MySQL中,创建存储过程的基本形式如下: CREATE PROCEDURE ...

  4. pyDes 实现 Python 版的 DES 对称加密/解密--转

    https://my.oschina.net/leejun2005/blog/586451 手头有个 Java 版的 DES 加密/解密程序,最近想着将其 Python 重构下,方便后续脚本解析,捣鼓 ...

  5. 60查找nanopim1plus的HDMI为720p输出的问题

    60查找nanopim1plus的HDMI为720p输出的问题 大文实验室/大文哥 壹捌陆捌零陆捌捌陆捌贰 21504965 AT qq.com 完成时间:2017/12/5 17:51 版本:V1. ...

  6. Docker在Ubuntu16.04上安装

    转自:http://blog.51cto.com/collen7788/2047800 1.添加Docker源 sudo apt-get update 2.增加CA证书 sudo apt-get in ...

  7. 360 你妈妈知道你跟Python存在兼容问题吗?

    最近在用Python2.7.6版本开发的的过程中发现了一个问题 提示:UnicodeDecodeError:'ascii' codec can't decode bytes 0xb0 刚开始以为是编码 ...

  8. dubbo-monitor安装及配置过程

    安装 1. 使用git下载(git clone https://github.com/alibaba/dubbo.git)或者从http://dubbo.io/下载源码 2. cd到dubbo的根目录 ...

  9. [转]最值得拥有的免费Bootstrap后台管理模板

    在PHP开发项目中,后台管理因为面向群体相对比较固定,大部分以实现业务逻辑和功能.使用Bootstrap后台模板可以让后端开发很轻松的就展现给客户一个响应式的后台,节约前端开发的时间.下面PHP程序员 ...

  10. IOS 11,UIWebView内容随状态栏高度下移,导致状态栏不透明

    解决方案: 方法1:在html中设置 <meta name="viewport" content="viewport-fit=cover,maximum-scale ...