首页 > 代码库 > django cbv

django cbv

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

简单用法:

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

子类化通用视图,

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

from django.views.generic import TemplateViewclass AboutView(TemplateView):    template_name = "about.html"        def get_context_data(self, **kwargs):        context = super().get_context_data(**kwargs)        #alter context         return context

ListView:

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

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

对数据模型进行筛选:

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

如果要进行传参的话:

# urls.pyfrom django.conf.urls import patternsfrom books.views import PublisherBookListurlpatterns = patterns(‘‘,    (r‘^books/([\w-]+)/$‘, PublisherBookList.as_view()),)# views.pyfrom django.shortcuts import get_object_or_404from django.views.generic import ListViewfrom books.models import Book, Publisherclass 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.pyfrom django.db import modelsclass 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()#URLConffrom django.conf.urls import patterns, urlfrom books.views import AuthorDetailViewurlpatterns = patterns(‘‘,    #...    url(r‘^authors/(?P<pk>\d+)/$‘, AuthorDetailView.as_view(), name=‘author-detail‘),)#Viewfrom django.views.generic import DetailViewfrom django.utils import timezonefrom books.models import Authorclass 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

包含post,get方法:

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

一个简单的contact form

# forms.pyfrom django import formsclass ContactForm(forms.Form):    name = forms.CharField()    message = forms.CharField(widget=forms.Textarea)    def send_email(self):        # 使用 self.cleaned_data 字典来发送一封邮件        pass# views.pyfrom myapp.forms import ContactFormfrom django.views.generic.edit import FormViewclass 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