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

Django-简述generic views

时间:2019-09-11 10:02:26      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:his   view   sel   temp   called   objects   tsv   detail   use   

Use generic views: Less code is better.

These views represent a common case of basic Web development: getting data from the database according to a parameter passed in the URL, loading a template and returning the rendered template. Because this is so common, Django provides a shortcut, called the "generic views" system.

Generic views abstract common patterns to the point where you don‘t even need to write Python code to write an app.

Let‘s convert our poll app to use the generic views system, so we can delete a bunch of our own code. We‘ll just have to take a few steps to make the conversion. We will:

  1. Convert the URLconf.
  2. Delete some of the old, unneeded views.
  3. Introduce new views based on Django‘s generic views.
# 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]


# def detail(request, question_id):
#     question = get_object_or_404(Question, pk=question_id)
#     return render(request, ‘polls/detail.html‘, {‘question‘: question})

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

 

  • 每个通用视图都需要知道它将作用于什么模型(models)。这是使用model属性提供的。
  • DetailView 通用视图期望从URL捕获的主键值被称为“pk”,因此我们将泛型视图的问题id更改为pk。

 

Django-简述generic views

标签:his   view   sel   temp   called   objects   tsv   detail   use   

原文地址:https://www.cnblogs.com/daemonFlY/p/11504149.html

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