0
点赞
收藏
分享

微信扫一扫

Django通用视图

小龟老师 2024-01-02 阅读 17
djangopython

有些视图反映基本的网络开发中的一个常见情况:根据 URL 中的参数从数据库中获取数据、载入模板文件然后返回渲染后的模板。 由于这种情况特别常见,通用视图将通用模式抽象到你甚至不需要编写Python代码来编写应用程序的程度。例如,ListView和DetailView泛型视图分别抽象了“显示对象列表”和“显示特定类型对象的详细页面”的概念。

以投票应用为例,关于投票应用的更多内容,请查看

Django创建投票应用-CSDN博客

首先重构polls/urls.py

from django.urls import path
from . import views

app_name = "polls"
urlpatterns = [
    path("", views.IndexView.as_view(), name="index"),
    path("<int:pk>/", views.DetailView.as_view(), name="detail"),
    path("<int:pk>/results/", views.ResultsView.as_view(), name="results"),
    path("<int:question_id>/vote/", views.vote, name="vote"),
]

我们将删除旧的 index, detail, 和 results 视图,并用 Django 的通用视图代替。

重构 polls/views.py 文件

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic

from .models import Choice, Question

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

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by("-pub_date")[:5]

class DetailView(generic.DetailView):
    model = Question
    template_name = "polls/detail.html"

class ResultsView(generic.DetailView):
    model = Question
    template_name = "polls/results.html"

def vote(request, question_id):
    ...  # same as above, no changes needed.

启动服务器,使用一下基于通用视图的新投票应用。

举报

相关推荐

0 条评论