• django cbv


    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

  • 相关阅读:
    Java method Exception throw with return instance.
    SQL Profiler Practice.
    FTP 文件 循环 Copy
    【SQL遗补】之 SET NOCOUNT (TransactSQL)
    【WinForm窗体控件开发】之三 窗体控件设计时属性Attribute
    【WinForm窗体控件开发】之三续 窗体控件设计时的事件属性
    【WinForm窗体控件开发】之二 简单的窗体控件
    解决删除DataGridView中数据引发的“DataGridView Default Error Dialog 错误”
    .NET开发WinCE程序之使用软键盘(System.WindowsCE.Forms命名空间)兼容WinCE和桌面操作系统之解决方案
    【C#遗补】之Char.IsDigit和Char.IsNumber的区别
  • 原文地址:https://www.cnblogs.com/tuifeideyouran/p/4206132.html
Copyright © 2020-2023  润新知