标题:django CBV | 作者: catfish | 时间:2019年12月28日
暂无法显示图片

目录

1,View类

2,ListView类

3,TemplateView类

4,DetailView类

5,RedirectView类

View类

这个类是所有视图类的父类,提供最基本的处理方法。使用方法如下:

from django.views.generic import View
from django.shortcuts import render

class BookDetailView(View):
    def get(self,request):
        reutrn render(request, 'index.html', locals())

    # 处理405错误
    def http_method_not_allowed(self,request):
        return HttpResponse("不支持get以外的其他请求!")

    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(self,request,*args,**kwargs)

首先会调用dispatch方法来判断是否调用get,或者post等html方法。如果没有对应的方法函数,会引发405状态码异常,并调用http_method_not_allowed函数。然后绑定相关url连接如下:

from django.urls import path
from blog.views import BookDetailView

urlpatterns = [
    path('book', BookDetailView.as_view(), name="book"),
]

如果使用基于类的视图,装饰器需要引入:

from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.generic import View

class BookDetailView(View):
    def get(self,request):
        return render(request, 'index.html', locals())

    # 处理405错误
    def http_method_not_allowed(self,request):
       return HttpResponse("不支持get以外的其他请求!")
        
    @method_decorator(login_required)    # 判断用户是否登录
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(self,request,*args,**kwargs)

但是一般情况下,我们并不经常重写dispatch函数。我们可以在类上面定义,上述代码等效于下列代码:

from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.generic import View

@method_decorator([login_required],name='dispatch')
class BookDetailView(View):
    def get(self,request):
        return render(request, 'index.html', locals())

    # 处理405错误
    def http_method_not_allowed(self,request):
       return HttpResponse("不支持get以外的其他请求!")

除此之外,你还可以在路由中修饰:

from django.contrib.auth.decorators import login_required, permission_required
from django.views.generic import TemplateView

from .views import VoteView

urlpatterns = [
    path('about/', login_required(TemplateView.as_view(template_name="secret.html"))),
    path('vote/', permission_required('polls.can_vote')(VoteView.as_view())),
]

ListView类

ListView类常用于某个界面展示列表页的视图。基本用法如下:

class ArticleListView(ListView):
    model = Article               # 对应的模型
    template_name = 'article_list.html'            # 对应的模板文件
    paginate_by = 10                      # 分页器
    context_object_name = 'articles'                # 模型对象数
    ordering = 'create_time'              # 排序方式
    page_kwarg = 'page'     # 每一页的参数

    def get_context_data(self, **kwargs):   # 返回一个带有参数的字典
        context = super(ArticleListView, self).get_context_data()
    	context['username'] = 'zhiliao'
    	return context

    # 无论是什么请求都会调用这个方法,默认返回all()
    def get_queryset(self):
    	return Article.objects.all()

在模板页面中可以写如下:

{% for article in articles %}
    {{ article.title }}   {{ username }}
    {{ article.content }}
{% empty %}
    <span>该列表为空</span>
{% endfor %}

TemplateView类

用于展示静态页面,使用方法如下:

from django.views.generic import TemplateView
from django.urls import path

urlpatterns = [
    path('about', TempateView.as_view(template_name='about.html')),
]

如果想在其中添加参数,可以使用:

from django.views.generic import TemplateView

class AboutView(TemplateView):
    template_name = 'about.html'

    def get_context_data(self, **kwargs):
        return {'phone':'0732-8888'}

然后到urls.py中映射视图即可。

DetailView类

用于展示单个个体的类。基本用法如下:

from django.utils import timezone
from django.views.generic.detail import DetailView

from articles.models import Article

class ArticleDetailView(DetailView):

    model = Article   # 对应模型
    context_object_name = 'object'   # {{ object.title}}
    template_name = 'blog/article_detail.html'

    def get_context_data(self, **kwargs):   # 添加字典
        context = super().get_context_data(**kwargs) 
        context['now'] = timezone.now()               # {{ now }}
        return context

示例urls.py:

from django.urls import path

from article.views import ArticleDetailView

urlpatterns = [
    path('article/<int:pk>/', ArticleDetailView.as_view(), name='article-detail'),
]

RedirectView类

示例views.py:

from django.shortcuts import get_object_or_404
from django.views.generic.base import RedirectView

from articles.models import Article

class ArticleCounterRedirectView(RedirectView):

    permanent = False   # 是否为永久重定向(301)
    query_string = True                                               # 是否传递get参数
    pattern_name = 'article-detail' # 反转name值, 或者使用url作为参数

示例urls.py:

from django.urls import path
from django.views.generic.base import RedirectView

from article.views import ArticleCounterRedirectView

urlpatterns = [
    path('counter/<int:pk>/', ArticleCounterRedirectView.as_view(), name='article-counter'), # 引入使用
    path('go-to-django/', RedirectView.as_view(url='https://djangoproject.com'), name='go-to-django'),  # 直接使用
]

 

我要评论

没有登录?请先登录后再评论

最新评论

暂无人评论,来抢个沙发吧!