django 提供了一系列现成的类视图,他们都继承自一个 View 基类(django.views.generic.base.View)。在这个基类里实现了与 URLs 的接口(as_view)、请求方法匹配(dispatch)和一些其他的基本功能。比如 RedirectView 实现了一个简单的 HTTP 重定向,TemplateView 给 View 添加了一个渲染模板的功能。

简单用法:

from django.conf.urls import patterns
from django.views.generic import TemplateView urlpatterns = patterns('',
(r'^about/', TemplateView.as_view(template_name="about.html")),
)

子类化通用视图,

一个 AboutView,他覆盖了 TemplateView 的模板属性和获取 Context 方法(这是使用 TemplateView 的一般做法):

from django.views.generic import TemplateView

class AboutView(TemplateView):
template_name = "about.html" def get_context_data(self, **kwargs):
context = super(AboutView, self).get_context_data(**kwargs)
#alter context
return context

ListView:

from django.views.generic import ListView
from books.models import Publisher class PublisherList(ListView):
model = Publisher

它会自动去寻找publiser_list.html页面作为模板,并在里面渲染{{publisher_list}}作为变量.

对数据模型进行筛选:

from django.views.generic import ListView
from books.models import Book class BookList(ListView):
queryset = Book.objects.order_by('-publication_date')
context_object_name = 'book_list'

如果要进行传参的话:

# urls.py
from django.conf.urls import patterns
from books.views import PublisherBookList urlpatterns = patterns('',
(r'^books/([\w-]+)/$', PublisherBookList.as_view()),
) # views.py
from django.shortcuts import get_object_or_404
from django.views.generic import ListView
from books.models import Book, Publisher class PublisherBookList(ListView): template_name = 'books/books_by_publisher.html' def get_queryset(self):
self.publisher = get_object_or_404(Publisher, name=self.args[0])
return Book.objects.filter(publisher=self.publisher)

保存时候的小动作:

# models.py
from django.db import models class Author(models.Model):
salutation = models.CharField(max_length=10)
name = models.CharField(max_length=200)
email = models.EmailField()
headshot = models.ImageField(upload_to='author_headshots')
last_accessed = models.DateTimeField() #URLConf from django.conf.urls import patterns, url
from books.views import AuthorDetailView urlpatterns = patterns('',
#...
url(r'^authors/(?P<pk>\d+)/$', AuthorDetailView.as_view(), name='author-detail'),
) #View from django.views.generic import DetailView
from django.utils import timezone
from books.models import Author class AuthorDetailView(DetailView): queryset = Author.objects.all() def get_object(self):
# Call the superclass
object = super(AuthorDetailView, self).get_object()
# Record the last accessed date
object.last_accessed = timezone.now()
object.save()
# Return the object
return object #Model
def get_absolute_url(self):
return reverse('student:systemMessageDetail', args=[self.pk])

包含post,get方法:

from django.http import HttpResponse
from django.views.generic import View class MyView(View):
def get(self, request):
# <view logic>
return HttpResponse('result')

一个简单的contact form

# forms.py
from django import forms class ContactForm(forms.Form):
name = forms.CharField()
message = forms.CharField(widget=forms.Textarea) def send_email(self):
# 使用 self.cleaned_data 字典来发送一封邮件
pass # views.py
from myapp.forms import ContactForm
from django.views.generic.edit import FormView class ContactView(FormView):
template_name = 'contact.html'
form_class = ContactForm
success_url = '/thanks/' def form_valid(self, form):
# 当有效的数据被 POST 进来以后,本方法就会被调用
# 本方法应当返回一个 HttpResponse.
form.send_email()
return super(ContactView, self).form_valid(form)

转载自http://www.pythontip.com/blog/post/12172/

一个简单的view

django cbv的更多相关文章

  1. Python/Django(CBV/FBV/ORM操作)

    Python/Django(CBV/FBV/ORM操作) CBV:url对应的类(模式) ##====================================CBV操作============ ...

  2. 源码解析Django CBV的本质

    Django CBV模式的源码解析 通常来说,http请求的本质就是基于Socket Django的视图函数,可以基于FBV模式,也可以基于CBV模式. 基于FBV的模式就是在Django的路由映射表 ...

  3. Django CBV和FBV

    Django CBV和FBV Django内部CBV内部接收方法操作: 1.通过客户端返回的请求头RequestMethod与RequesrtURL,会以字符串形式发送到服务器端. 2.取到值后通过d ...

  4. DRF框架(一)——restful接口规范、基于规范下使用原生django接口查询和增加、原生Django CBV请求生命周期源码分析、drf请求生命周期源码分析、请求模块request、渲染模块render

    DRF框架    全称:django-rest framework 知识点 1.接口:什么是接口.restful接口规范 2.CBV生命周期源码 - 基于restful规范下的CBV接口 3.请求组件 ...

  5. django CBV视图源码分析

    典型FBV视图例子 url路由系统 from django.conf.urls import url from django.contrib import admin from luffycity.v ...

  6. Python Django CBV下的通用视图函数

    ListView TemplateView DetailView 之前的代码实例基本上都是基于FBV的模式来撰写的,好处么,当然就是简单粗暴..正如: def index(request): retu ...

  7. $Django cbv源码分析 djangorestframework框架之APIView源码分析

    1 CBV的源码分析 #视图 class login (View): pass #路由 url(r'^books/$', views.login.as_view()) #阅读源码: #左侧工程栏--- ...

  8. [django]cbv方式

    cbv的方式 1.简单的url from django.views.generic import TemplateView path('', TemplateView.as_view(template ...

  9. django ----CBV中加装饰器

    CBV中加装饰器 from django import views from django.utils.decorators import method_decorator def login_aut ...

  10. django CBV和FBV写法总结

    一.FBV function base views 平常我们的写法,一个URL对应一个视图函数 二.CBV 1.url 配置 path('test/',views.CBVTest.as_views() ...

随机推荐

  1. 如何注册Uber司机,加入uber(全国版最新最详细注册流程)

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...

  2. Light Bulb(三分)

    ZOJ Problem Set - 3203 Light Bulb Time Limit: 1 Second      Memory Limit: 32768 KB Compared to wildl ...

  3. 实验记录一 初步接触cortex-M3

    应该说老早就在接触cortex-M3了.曾经没想到会接触嵌入式,结果由于导师的缘故.在选择项目管理时,就呵呵了.不废话.搭配环境非常easy,纯粹傻瓜式.可由于自己的马虎,却让自己一直困惑. 记得在前 ...

  4. LCM Cardinality

    http://acm.hust.edu.cn/vjudge/contest/view.action?cid=31675#problem/E 暴力 // File Name: uva10892.cpp ...

  5. 倒计时IE6+

    很简单的 下面是我为了做多个倒计时更改之后的 dome 下载链接   兼容 IE7以上 IE6没测试应该没问题 http://yunpan.cn/cf29rxmGKuMyJ  提取码 ca61

  6. window.showModalDialog刷新父窗口和本窗口的方法及注意

    window.showModalDialog刷新父窗口和本窗口的方法及注意:   一.刷新父窗口的方法:    A.使用window.returnValue给父窗口传值,然后根据值判断是否刷新. 在w ...

  7. Assertion failure in -[UIView layoutSublayersOfLayer:]

    Assertion failure in -[UIView layoutSublayersOfLayer:], /SourceCache/UIKit/UIKit-2935.137/UIView.m:8 ...

  8. handlebar.js使用

    官方网站:http://handlebarsjs.com/ 下载及查看使用帮助,或者用百度cdn引用 一.定义模板 <script id="entry-template" t ...

  9. POJ 3167 Cow Patterns(模式串浮动匹配)

    题目链接:http://poj.org/problem?id=3167 题意:模式串可以浮动的模式匹配问题给出模式串的相对大小,需要找出模式串匹配次数和位置. 思路:统计比当前数小,和于当前数相等的, ...

  10. 5.6.3 String类型

    String类型是字符串的对象包装类型,可以像下面这样使用String构造函数来创建. var stringObject = new String("hello world"); ...