zoukankan      html  css  js  c++  java
  • django-基于类的通用视图

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

    ListView类:要在index.html中用列表显示对象

        <ul>
            {% for question in latest_question_list %}
                <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
            {% endfor %}
        </ul>    

    改写前后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'),

    也可以没有get_queryset方法,但是需要指定model,如果不写上下文传递的对象默认为“object_list”

    TemplateView类:没有动态数据,只显示模板about.html的视图

    # some_app/views.py
    from django.views.generic import TemplateView
    
    class AboutView(TemplateView):
        template_name = "about.html"
    # urls.py
    from django.urls import path
    from some_app.views import AboutView
    
    urlpatterns = [
        path('about/', AboutView.as_view()),
    ]
  • 相关阅读:
    [程序员代码面试指南]数组和矩阵问题-未排序正数数组中累加和为给定值的最长子数组长度
    [Mysql]知识点
    [SSM项目]一-Eclipse 搭建marven-web项目 hello world!
    [BZOJ2252]矩阵距离(BFS)
    [Spring实战笔记]4面向切面编程的Spring-代理
    [程序员代码面试指南]数组和矩阵问题-找到无序数组中最小的k个数(堆排序)
    [Java]刷题中的Java基础
    MySql的大小写问题
    MySql密码丢失
    MySql的rpm安装
  • 原文地址:https://www.cnblogs.com/staff/p/12444184.html
Copyright © 2011-2022 走看看