码迷,mamicode.com
首页 > 其他好文 > 详细

django-基于类的视图

时间:2020-03-08 19:58:59      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:self   参数   views   latest   render   基于   http   传递   context   

所有视图继承自View类,例如,RedirectView用于HTTP重定向,TemplateView扩展基类使它能渲染模板。

例如index首页--改成View类

改写前后urls.py------

前:

from django.urls import path
from . import views

app_name = ‘polls‘
urlpatterns = [
    path(‘‘, views.index, name=‘index‘)
]

后:

from django.urls import path
from . import views

app_name = ‘polls‘
urlpatterns = [
    path(‘‘, views.IndexView.as_view(), name=‘index‘)
]

改写前后Views.py----

前:

from django.shortcuts import render
from .models import Question

def index(request):
    latest_question_list = Question.objects.order_by(‘-pub_date‘)[:5]
    context = {‘latest_question_list‘: latest_question_list}
    return render(request, ‘polls/index.html‘, context)

后:

from django.views import generic

class IndexView(generic.ListView):
    template_name = ‘polls/index.html‘
    context_object_name = ‘latest_question_list‘

    def get_queryset(self):
        return Question.objects.filter().order_by(‘-pub_date‘)[:5]

也可以把IndexView里的属性写到urls.py中:任何传递到 as_view()  的参数将覆盖在类上设置的属性

path(‘‘, views.IndexView.as_view(template_name=‘polls/index.html‘), name=‘index‘),

1231

 

django-基于类的视图

标签:self   参数   views   latest   render   基于   http   传递   context   

原文地址:https://www.cnblogs.com/staff/p/12444184.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!