The Django Book

Chapter 9: Generic Views

SmNHmB <a href=”http://ynplfxmsfjas.com/“>ynplfxmsfjas</a>, [url=http://afzikbuhbzzy.com/]afzikbuhbzzy[/url], [link=http://rmvxarlrgmyq.com/]rmvxarlrgmyq[/link], http://lxjsvkwlvktf.com/

Here again is a recurring theme of this book: at its worst, Web development is boring and monotonous. So far, weve covered how Django tries to take away some of that monotony at the model and template layers, but Web developers also experience this boredom at the view level.

oMhafb <a href=”http://wxqvnkowipsh.com/“>wxqvnkowipsh</a>, [url=http://jgrcakhpncly.com/]jgrcakhpncly[/url], [link=http://rmojkmnglmff.com/]rmojkmnglmff[/link], http://npmxesmysuxb.com/

Djangos generic views were developed to ease that pain. They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to write too much code. In fact, nearly every view example in the preceding chapters could be rewritten with the help of generic views.

ESWfz2 <a href=”http://qhhwejzlvhdg.com/“>qhhwejzlvhdg</a>, [url=http://dgjhcvixtkbj.com/]dgjhcvixtkbj[/url], [link=http://zzqibhslmuii.com/]zzqibhslmuii[/link], http://snkoxhyeojqh.com/

Chapter 8 touched briefly on how youd go about making a view generic. To review, we can recognize certain common tasks, like displaying a list of objects, and write code that displays a list of any object. Then the model in question can be passed as an extra argument to the URLconf.

2fPTAc <a href=”http://llijnkwkoyyd.com/“>llijnkwkoyyd</a>, [url=http://xxyyyrvmmlqq.com/]xxyyyrvmmlqq[/url], [link=http://dunaskbxxsll.com/]dunaskbxxsll[/link], http://olwmgfgxzaof.com/

Django ships with generic views to do the following:

PaYeM0 <a href=”http://dhmykebhsimg.com/“>dhmykebhsimg</a>, [url=http://hyizkgihaqdi.com/]hyizkgihaqdi[/url], [link=http://jcinmepstroe.com/]jcinmepstroe[/link], http://svbiputphxel.com/

  • Perform common simple tasks: redirect to a different page and render a given template.

  • 瀹屾垚甯哥敤鐨勭畝鍗曚换鍔★細閲嶅畾鍚戝埌鍙︿竴涓〉闈互鍙婃覆鏌撲竴涓寚瀹氱殑妯℃澘銆

  • Display list and detail pages for a single object. The event_list and entry_list views from Chapter 8 are examples of list views. A single event page is an example of what we call a detail view.

38fEhz <a href=”http://cajhjkeswyws.com/“>cajhjkeswyws</a>, [url=http://bcggwqooqnsq.com/]bcggwqooqnsq[/url], [link=http://ittkllncleip.com/]ittkllncleip[/link], http://zfhojpnwcklx.com/

  • Present date-based objects in year/month/day archive pages, associated detail, and latest pages. The Django Weblogs (http://www.djangoproject.com/weblog/) year, month, and day archives are built with these, as would be a typical newspapers archives.

  • 鍛堢幇鍩轰簬鏃ユ湡鐨勬暟鎹殑骞/鏈/鏃ュ綊妗i〉闈紝鍏宠仈鐨勮鎯呴〉闈紝鏈鏂伴〉闈€侱jango Weblogs (http://www.djangoproject.com/weblog/)鐨勫勾銆佹湀銆佹棩鐨勫綊妗e氨鏄娇鐢ㄩ氱敤瑙嗗浘 鏋舵瀯鐨勶紝灏卞儚鏄吀鍨嬬殑鏂伴椈鎶ョ焊褰掓。銆

  • Allow users to create, update, and delete objects with or without authorization.

Pnx4JT <a href=”http://uokrhwbsdkgc.com/“>uokrhwbsdkgc</a>, [url=http://qbsfadvarxud.com/]qbsfadvarxud[/url], [link=http://gwdbaeqxnhlf.com/]gwdbaeqxnhlf[/link], http://nxukqcjxxtly.com/

Taken together, these views provide easy interfaces to perform the most common tasks developers encounter.

i8AMSk <a href=”http://svhztxsiryev.com/“>svhztxsiryev</a>, [url=http://xhznnmbnuzku.com/]xhznnmbnuzku[/url], [link=http://gqqhpwyksfhs.com/]gqqhpwyksfhs[/link], http://rcpuvnqhetvh.com/

Using Generic Views

cSp6KO <a href=”http://zjtnkayajtcn.com/“>zjtnkayajtcn</a>, [url=http://skkxesnzsack.com/]skkxesnzsack[/url], [link=http://sakmtrjlashw.com/]sakmtrjlashw[/link], http://fkctfgdjzsjl.com/

All of these views are used by creating configuration dictionaries in your URLconf files and passing those dictionaries as the third member of the URLconf tuple for a given pattern.

EWMqsf <a href=”http://zqlypjgfuqno.com/“>zqlypjgfuqno</a>, [url=http://wlgybeuamsyg.com/]wlgybeuamsyg[/url], [link=http://pavtyxnjmwtt.com/]pavtyxnjmwtt[/link], http://rmdzoqinkave.com/

For example, heres a simple URLconf you could use to present a static about page:

渚嬪锛屼笅闈㈡槸涓涓憟鐜伴潤鎬佲滃叧浜庘濋〉闈㈢殑URLconf锛

from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
    ('^about/$', direct_to_template, {
        'template': 'about.html'
    })
)

Though this might seem a bit magical at first glance look, a view with no code! , its actually exactly the same as the examples in Chapter 8: the direct_to_template view simply grabs information from the extra-parameters dictionary and uses that information when rendering the view.

涓鐪肩湅涓婂幓浼间箮鏈夌偣涓嶅彲鎬濊锛屼笉闇瑕佺紪鍐欎唬鐮佺殑瑙嗗浘锛佸畠鍜岀鍏珷涓殑渚嬪瓙瀹屽叏涓鏍凤細 direct_to_template 瑙嗗浘浠庡弬鏁颁腑鑾峰彇娓叉煋瑙嗗浘鎵闇鐨勭浉鍏充俊鎭

Because this generic view and all the others is a regular view functions like any other, we can reuse it inside our own views. As an example, lets extend our about example to map URLs of the form /about/<whatever>/ to statically rendered about/<whatever>.html . Well do this by first modifying the URLconf to point to a view function:

鍥犱负閫氱敤瑙嗗浘閮芥槸鏍囧噯鐨勮鍥惧嚱鏁帮紝鎴戜滑鍙互鍦ㄦ垜浠嚜宸辩殑瑙嗗浘涓噸鐢ㄥ畠銆備緥濡傦紝鎴戜滑鎵╁睍 about渚嬪瓙鎶婃槧灏勭殑URL浠 /about/<whatever>/ 鍒颁竴涓潤鎬佹覆鏌 about/<whatever>.html 銆 鎴戜滑棣栧厛淇敼URL閰嶇疆鍒版柊鐨勮鍥惧嚱鏁帮細

from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
**from mysite.books.views import about_pages**

urlpatterns = patterns('',
    ('^about/$', direct_to_template, {
        'template': 'about.html'
    }),
    **('^about/(w+)/$', about_pages),**
)

Next, well write the about_pages view:

鎺ヤ笅鏉ワ紝鎴戜滑缂栧啓 about_pages 瑙嗗浘鐨勪唬鐮侊細

from django.http import Http404
from django.template import TemplateDoesNotExist
from django.views.generic.simple import direct_to_template

def about_pages(request, page):
    try:
        return direct_to_template(request, template="about/%s.html" % page)
    except TemplateDoesNotExist:
        raise Http404()

Here were treating direct_to_template like any other function. Since it returns an HttpResponse , we can simply return it as-is. The only slightly tricky business here is dealing with missing templates. We dont want a nonexistent template to cause a server error, so we catch TemplateDoesNotExist exceptions and return 404 errors instead.

鍦ㄨ繖閲屾垜浠薄浣跨敤鍏朵粬鍑芥暟涓鏍蜂娇鐢 direct_to_template 銆傚洜涓哄畠杩斿洖涓涓 HttpResponse 瀵硅薄锛屾垜浠彧闇瑕佺畝鍗曠殑杩斿洖瀹冨氨濂戒簡銆傛湁涓涓◢寰鏉傜殑鍦版柟锛岃澶勭悊娌℃湁鎵惧埌妯℃澘鐨勬儏鍐点 鎴戜滑涓嶅笇鏈涗竴涓笉瀛樺湪鐨勬ā鏉垮紩鍙戞湇鍔″櫒閿欒锛屾墍浠ユ垜浠崟鎹 TempalteDoesNotExist 寮傚父 骞惰繑鍥404閿欒銆

Is There a Security Vulnerability Here?

杩欓噷鏈夋病鏈夊畨鍏ㄦч棶棰橈紵

Sharp-eyed readers may have noticed a possible security hole: were constructing the template name using interpolated content from the browser (template="about/%s.html" % page ). At first glance, this looks like a classic directory traversal vulnerability (discussed in detail in Chapter 19). But is it really?

鐪煎皷鐨勮鑰呭彲鑳藉凡缁忔敞鎰忓埌涓涓彲鑳界殑瀹夊叏婕忔礊锛氭垜浠洿鎺ヤ娇鐢ㄤ粠瀹㈡埛绔祻瑙堝櫒鏉ョ殑鏁版嵁鏋勯 妯℃澘鍚嶇О(template="about/%s.html" % page )銆備箥鐪嬭捣鏉ワ紝杩欏儚鏄竴涓粡鍏哥殑 鐩綍閬嶅巻锛坉irectory traversal锛 鏀诲嚮锛堣鎯呰鐪嬬鍗佷節绔狅級銆備簨瀹炵湡鏄繖鏍峰悧锛

Not exactly. Yes, a maliciously crafted value of page could cause directory traversal, but although page is taken from the request URL, not every value will be accepted. They key is in the URLconf: were using the regular expression \w+ to match the page part of the URL, and \w only accepts letters and numbers. Thus, any malicious characters (dots and slashes, here) will be rejected by the URL resolver before they reach the view itself.

瀹屽叏涓嶆槸銆傛槸鐨勶紝涓涓伓鎰忕殑 page 鍊煎彲浠ュ鑷寸洰褰曡法瓒婏紝浣嗘槸灏界 page 浠 璇锋眰鐨刄RL涓幏鍙栫殑锛屽苟涓嶆槸鎵鏈夌殑鍊奸兘琚帴鍙椼傝繖灏辨槸URL閰嶇疆鐨勫叧閿墍鍦細鎴戜滑浣跨敤姝e垯琛ㄨ揪寮 \w+ 鏉ヤ粠URL閲屽尮閰 page 锛岃 \w 鍙帴鍙楀瓧绗﹀拰鏁板瓧銆傚洜姝わ紝浠讳綍鎭舵剰鐨勫瓧绗 锛堜緥濡傚湪杩欓噷鏄偣 . 鍜屾鏂滅嚎 / 锛夊皢鍦║RL瑙f瀽鏃惰鎷掔粷锛屾牴鏈笉浼氫紶閫掔粰瑙嗗浘鍑芥暟銆

Generic Views of Objects

瀵硅薄鐨勯氱敤瑙嗗浘

The direct_to_template certainly is useful, but Djangos generic views really shine when it comes to presenting views on your database content. Because its such a common task, Django comes with a handful of built-in generic views that make generating list and detail views of objects incredibly easy.

direct_to_template 姣棤鐤戦棶鏄潪甯告湁鐢ㄧ殑锛屼絾Django閫氱敤瑙嗗浘鏈鏈夌敤鐨勬槸鍦ㄥ憟鐜 鏁版嵁搴撲腑鐨勬暟鎹傚洜涓鸿繖涓簲鐢ㄥ疄鍦ㄥお鏅亶浜嗭紝Django甯︽湁寰堝鍐呭缓鐨勯氱敤瑙嗗浘鏉ュ府鍔╀綘寰堝鏄 鐨勭敓鎴愬璞$殑鍒楄〃鍜屾槑缁嗚鍥俱

Lets take a look at one of these generic views: the object list view. Well be using this Publisher object from Chapter 5:

璁╂垜浠厛鐪嬬湅鍏朵腑鐨勪竴涓氱敤瑙嗗浘锛氬璞″垪琛ㄨ鍥俱傛垜浠娇鐢ㄧ浜旂珷涓殑 Publisher 鏉ヤ妇渚嬶細

class Publisher(models.Model):
    name = models.CharField(maxlength=30)
    address = models.CharField(maxlength=50)
    city = models.CharField(maxlength=60)
    state_province = models.CharField(maxlength=30)
    country = models.CharField(maxlength=50)
    website = models.URLField()

    def __str__(self):
        return self.name

    class Meta:
        ordering = ["-name"]

    class Admin:
        pass

To build a list page of all books, wed use a URLconf along these lines:

瑕佷负鎵鏈夌殑涔︾睄鍒涘缓涓涓垪琛ㄩ〉闈紝鎴戜滑浣跨敤涓嬮潰鐨刄RL閰嶇疆锛

from django.conf.urls.defaults import *
from django.views.generic import list_detail
from mysite.books.models import Publisher

publisher_info = {
    "queryset" : Publisher.objects.all(),
}

urlpatterns = patterns('',
    (r'^publishers/$', list_detail.object_list, publisher_info)
)

Thats all the Python code we need to write. We still need to write a template, however. We could explicitly tell the object_list view which template to use by including a template_name key in the extra arguments dictionary, but in the absence of an explicit template Django will infer one from the objects name. In this case, the inferred template will be "books/publisher_list.html" the books part comes from the name of the app that defines the model, while the publisher bit is just the lowercased version of the models name.

杩欏氨鏄墍瑕佺紪鍐欑殑鎵鏈塒ython浠g爜銆傚綋鐒讹紝鎴戜滑杩橀渶瑕佺紪鍐欎竴涓ā鏉裤傛垜浠彲浠ラ氳繃鍦ㄩ澶栧弬鏁 瀛楀吀閲屽寘鍚 template_name 鏉ユ竻妤氱殑鍛婅瘔 object_list 瑙嗗浘浣跨敤鍝釜妯℃澘锛屼絾鏄 鐢变簬Django鍦ㄤ笉缁欏畾妯℃澘鐨勬椂鍊欎細鐢ㄥ璞$殑鍚嶇О鎺ㄥ鍑轰竴涓傚湪杩欎釜渚嬪瓙涓紝杩欎釜鎺ㄥ鍑虹殑妯℃澘鍚嶇О 灏嗘槸 "books/publisher_list.html" 锛屽叾涓璪ooks閮ㄥ垎鏄畾涔夎繖涓ā鍨嬬殑app鐨勫悕绉帮紝 publisher閮ㄥ垎鏄繖涓ā鍨嬪悕绉扮殑灏忓啓銆

This template will be rendered against a context containing a variable called object_list that contains all the book objects. A very simple template might look like the following:

杩欎釜妯℃澘灏嗘寜鐓 context 涓寘鍚殑鍙橀噺 object_list 鏉ユ覆鏌擄紝杩欎釜鍙橀噺鍖呭惈鎵鏈夌殑涔︾睄瀵硅薄銆 涓涓潪甯哥畝鍗曠殑妯℃澘鐪嬭捣鏉ヨ薄涓嬮潰杩欐牱锛

{% extends "base.html" %}

{% block content %}
    <h2>Publishers</h2>
    <ul>
        {% for publisher in object_list %}
            <li>{{ publisher.name }}</li>
        {% endfor %}
    </ul>
{% endblock %}

Thats really all there is to it. All the cool features of generic views come from changing the info dictionary passed to the generic view. Appendix D documents all the generic views and all their options in detail; the rest of this chapter will consider some of the common ways you might customize and extend generic views.

杩欏氨鏄墍鏈夎鍋氱殑浜嬨傝浣跨敤閫氱敤瑙嗗浘閰烽叿鐨勭壒鎬у彧闇瑕佷慨鏀瑰弬鏁板瓧鍏稿苟浼犻掔粰閫氱敤瑙嗗浘鍑芥暟銆 闄勫綍D鏄氱敤瑙嗗浘鐨勫畬鍏ㄥ弬鑰冭祫鏂欙紱鏈珷鎺ヤ笅鏉ョ殑绔犺妭灏嗚鍒拌嚜瀹氫箟鍜屾墿灞曢氱敤瑙嗗浘鐨勪竴浜涙柟娉曘

Extending Generic Views

鎵╁睍閫氱敤瑙嗗浘

Theres no question that using generic views can speed up development substantially. In most projects, however, there comes a moment when the generic views no longer suffice. Indeed, the most common question asked by new Django developers is how to make generic views handle a wider array of situations.

姣棤鐤戦棶锛屼娇鐢ㄩ氱敤瑙嗗浘鍙互鍏呭垎鍔犲揩寮鍙戦熷害銆傜劧鑰岋紝鍦ㄥ鏁扮殑宸ョ▼涓紝涔熶細鍑虹幇閫氱敤瑙嗗浘涓嶈兘 婊¤冻闇姹傜殑鎯呭喌銆傚疄闄呬笂锛屽垰鎺ヨЕDjango鐨勫紑鍙戣呮渶甯歌鐨勯棶棰樺氨鏄庢牱浣跨敤閫氱敤瑙嗗浘鏉ュ鐞嗘洿澶氱殑鎯呭喌銆

Luckily, in nearly every one of these cases, there are ways to simply extend generic views to handle a larger array of use cases. These situations usually fall into a handful of patterns dealt with in the sections that follow.

DNJEsI <a href=”http://xjeubrblziif.com/“>xjeubrblziif</a>, [url=http://dobvanweoamc.com/]dobvanweoamc[/url], [link=http://djyiudlubona.com/]djyiudlubona[/link], http://lixowftpfyrv.com/

Making Friendly Template Contexts

鍒朵綔鍙嬪ソ鐨勬ā鏉緾ontext

You might have noticed that sample publisher list template stores all the books in a variable named object_list . While this works just fine, it isnt all that friendly to template authors: they have to just know that theyre dealing with books here. A better name for that variable would be publisher_list ; that variables content is pretty obvious.

GopzWR <a href=”http://wyzfvmcuticl.com/“>wyzfvmcuticl</a>, [url=http://jxzqmqdmwetz.com/]jxzqmqdmwetz[/url], [link=http://piilbiaihfax.com/]piilbiaihfax[/link], http://htyxquhhvexk.com/

We can change the name of that variable easily with the template_object_name argument:

8Vyjss <a href=”http://rhhhrvhkabeq.com/“>rhhhrvhkabeq</a>, [url=http://ahvmqfezgjmk.com/]ahvmqfezgjmk[/url], [link=http://smovmqdvshdx.com/]smovmqdvshdx[/link], http://vibqzvjswygw.com/

publisher_info = {
    "queryset" : Publisher.objects.all(),
    **"template_object_name" : "publisher",**
}

urlpatterns = patterns('',
    (r'^publishers/$', list_detail.object_list, publisher_info)
)

Providing a useful template_object_name is always a good idea. Your coworkers who design templates will thank you.

浣跨敤鏈夌敤鐨 template_object_name 鎬绘槸涓ソ鎯虫硶銆備綘鐨勮璁℃ā鏉跨殑鍚堜綔浼欎即浼氭劅璋綘鐨勩

Adding Extra Context

娣诲姞棰濆鐨凜ontext

Often you simply need to present some extra information beyond that provided by the generic view. For example, think of showing a list of all the other publishers on each publisher detail page. The object_detail generic view provides the publisher to the context, but it seems theres no way to get a list of all publishers in that template.

浣犲父甯搁渶瑕佸憟鐜版瘮閫氱敤瑙嗗浘鎻愪緵鐨勬洿澶氱殑棰濆淇℃伅銆備緥濡傦紝鑰冭檻涓涓嬪湪姣忎釜鍑虹増鍟嗛〉闈㈠疄鐜版墍鏈夊叾浠 鍑虹増鍟嗗垪琛ㄣ object_detail 閫氱敤瑙嗗浘鎻愪緵浜嗗嚭鐗堝晢鍒癱ontext锛屼絾鏄湅璧锋潵娌℃湁鍔炴硶鍦ㄦā鏉夸腑 鑾峰彇 鎵鏈 鍑虹増鍟嗗垪琛ㄣ

But there is: all generic views take an extra optional parameter, extra_context . This is a dictionary of extra objects that will be added to the templates context. So, to provide the list of all publishers on the detail detail view, wed use an info dict like this:

杩欐槸瑙e喅鏂规硶锛氭墍鏈夌殑閫氱敤瑙嗗浘閮芥湁涓涓澶栫殑鍙夊弬鏁 extra_context 銆傝繖涓弬鏁版槸涓涓瓧鍏告暟鎹被鍨嬶紝鍖呭惈瑕佹坊鍔犲埌妯℃澘鐨刢ontext涓殑棰濆鐨勫璞°傛墍浠ヨ鎻愪緵鎵鏈夌殑鍑虹増鍟嗘槑缁嗙粰瑙嗗浘锛屾垜浠氨鐢ㄨ繖鏍风殑info瀛楀吀锛

publisher_info = {
    "queryset" : Publisher.objects.all(),
    "template_object_name" : "publisher",
    **"extra_context" : {"book_list" : Book.objects.all()}**
}

This would populate a {{ book_list }} variable in the template context. This pattern can be used to pass any information down into the template for the generic view. Its very handy.

杩欐牱灏辨妸涓涓 {{ book_list }} 鍙橀噺鏀惧埌妯℃澘鐨刢ontext涓傝繖涓柟娉曞彲浠ョ敤鏉ヤ紶閫掍换鎰忔暟鎹 鍒伴氱敤瑙嗗浘妯℃澘涓幓锛岄潪甯告柟渚裤

However, theres actually a subtle bug here can you spot it?

11BuSm <a href=”http://eqbfztxatswg.com/“>eqbfztxatswg</a>, [url=http://cqyvbzdkmltn.com/]cqyvbzdkmltn[/url], [link=http://crybwpchprla.com/]crybwpchprla[/link], http://zsruvjbcerqm.com/

The problem has to do with when the queries in extra_context are evaluated. Because this example puts Publisher.objects.all() in the URLconf, it will be evaluated only once (when the URLconf is first loaded). Once you add or remove publishers, youll notice that the generic view doesnt reflect those changes until you reload the Web server (see Caching and QuerySets in Appendix C for more information about when QuerySets are cached and evaluated).

鎴戜滑鐜板湪鏉ョ湅涓涓嬶紝 extra_context 閲屽寘鍚暟鎹簱鏌ヨ鐨勯棶棰樸傚洜涓哄湪杩欎釜渚嬪瓙涓紝鎴戜滑鎶 Publisher.objects.all() 鏀惧湪URLconf涓紝瀹冨彧浼氭墽琛屼竴娆★紙褰揢RLconf绗竴娆″姞杞界殑鏃跺欙級銆傚綋浣犳坊鍔犳垨鍒犻櫎鍑虹増鍟嗭紝浣犱細鍙戠幇鍦ㄩ噸鍚疻eb鏈嶅姟鍣ㄤ箣鍓嶏紝閫氱敤瑙嗗浘涓嶄細鍙嶆槧鍑鸿繖浜涗慨鏀圭殑锛堟湁鍏砆uerySet浣曟椂琚紦瀛樺拰璧嬪肩殑鏇村淇℃伅璇峰弬鑰冮檮褰旵涓滅紦瀛樹笌鏌ヨ闆嗏濅竴鑺傦級銆

Note

澶囨敞

This problem doesnt apply to the queryset generic view argument. Since Django knows that particular QuerySet should never be cached, the generic view takes care of clearing the cache when each view is rendered.

PHysZ7 <a href=”http://jbnqwfshbxue.com/“>jbnqwfshbxue</a>, [url=http://igfjyorkpypm.com/]igfjyorkpypm[/url], [link=http://wkdyrkxwmdfo.com/]wkdyrkxwmdfo[/link], http://wjhpynkhkixt.com/

The solution is to use a callback in extra_context instead of a value. Any callable (i.e., a function) thats passed to extra_context will be evaluated when the view is rendered (instead of only once). You could do this with an explicitly defined function:

瑙e喅杩欎釜闂鐨勫姙娉曟槸鍦 extra_context 涓敤涓涓洖璋冿紙callback锛夋潵 浠f浛浣跨敤涓涓彉閲忋備换浣曞彲浠ヨ皟鐢ㄧ殑瀵硅薄锛堜緥濡備竴涓嚱鏁帮級鍦ㄤ紶閫掔粰 extra_context 鍚庨兘浼氬湪姣忔瑙嗗浘娓叉煋鍓嶆墽琛岋紙鑰屼笉鏄彧鎵ц涓娆★級銆 浣犲彲浠ヨ薄杩欐牱瀹氫箟涓涓嚱鏁帮細

def get_books():
    return Book.objects.all()

publisher_info = {
    "queryset" : Publisher.objects.all(),
    "template_object_name" : "publisher",
    "extra_context" : **{"book_list" : get_books}**
}

or you could use a less obvious but shorter version that relies on the fact that Publisher.objects.all is itself a callable:

O2zMLs <a href=”http://imijpqyscyzu.com/“>imijpqyscyzu</a>, [url=http://isrvqdjbewfq.com/]isrvqdjbewfq[/url], [link=http://tiwdtcivjwov.com/]tiwdtcivjwov[/link], http://wlgvlcjtvply.com/

publisher_info = {
    "queryset" : Publisher.objects.all(),
    "template_object_name" : "publisher",
    "extra_context" : **{"book_list" : Book.objects.all}**
}

Notice the lack of parentheses after Book.objects.all ; this references the function without actually calling it (which the generic view will do later).

np4DMd <a href=”http://hbsnjcfoizvz.com/“>hbsnjcfoizvz</a>, [url=http://wdikbtkrqjrv.com/]wdikbtkrqjrv[/url], [link=http://hrfbyhalrzta.com/]hrfbyhalrzta[/link], http://joxjwznpivhb.com/

Viewing Subsets of Objects

8LlhZj <a href=”http://wzekxqnfpltm.com/“>wzekxqnfpltm</a>, [url=http://nfqbyffbfkil.com/]nfqbyffbfkil[/url], [link=http://byygkbksdadj.com/]byygkbksdadj[/link], http://xbrpupjsjpvs.com/

Now lets take a closer look at this queryset key weve been using all along. Most generic views take one of these queryset arguments its how the view knows which set of objects to display (see Selecting Objects in Chapter 5 for an introduction to QuerySets, and see Appendix C for the complete details).

鐜板湪璁╂垜浠潵浠旂粏鐪嬬湅杩欎釜 queryset 銆傚ぇ澶氭暟閫氱敤瑙嗗浘鏈変竴涓 queryset 鍙傛暟锛岃繖涓弬鏁板憡璇夎鍥捐鏄剧ず瀵硅薄鐨勯泦鍚 锛堟湁鍏砆uerySet鐨勮В閲婅鐪嬬浜旂珷鐨 鈥滈夋嫨瀵硅薄鈥濈珷鑺傦紝璇︾粏璧勬枡璇峰弬鐪嬮檮褰旵锛夈

To pick a simple example, we might want to order a list of books by publication date, with the most recent first:

bQLEb6 <a href=”http://smcfsnorksba.com/“>smcfsnorksba</a>, [url=http://aruhrbpgpnzq.com/]aruhrbpgpnzq[/url], [link=http://poapiucigzvo.com/]poapiucigzvo[/link], http://yqctgzvjhqfl.com/

book_info = {
    "queryset" : Book.objects.all().order_by("-publication_date"),
}

urlpatterns = patterns('',
    (r'^publishers/$', list_detail.object_list, publisher_info),
    **(r'^books/$', list_detail.object_list, book_info),**
)

Thats a pretty simple example, but it illustrates the idea nicely. Of course, youll usually want to do more than just reorder objects. If you want to present a list of books by a particular publisher, you can use the same technique:

杩欐槸涓涓浉褰撶畝鍗曠殑渚嬪瓙锛屼絾鏄緢璇存槑闂銆傚綋鐒讹紝浣犻氬父杩樻兂鍋氭瘮閲嶆柊鎺掑簭鏇村鐨勪簨銆 濡傛灉浣犳兂瑕佸憟鐜版煇涓壒瀹氬嚭鐗堝晢鍑虹増鐨勬墍鏈変功绫嶅垪琛紝浣犲彲浠ヤ娇鐢ㄥ悓鏍风殑鎶鏈細

**apress_books = {**
    **"queryset": Book.objects.filter(publisher__name="Apress Publishing"),**
    **"template_name" : "books/apress_list.html"**
**}**

urlpatterns = patterns('',
    (r'^publishers/$', list_detail.object_list, publisher_info),
    **(r'^books/apress/$', list_detail.object_list, apress_books),**
)

Notice that along with a filtered queryset , were also using a custom template name. If we didnt, the generic view would use the same template as the vanilla object list, which might not be what we want.

娉ㄦ剰 鍦ㄤ娇鐢ㄤ竴涓繃婊ょ殑 queryset 鐨勫悓鏃讹紝鎴戜滑杩樹娇鐢ㄤ竴涓嚜瀹氫箟鐨勬ā鏉垮悕绉般 濡傛灉鎴戜滑涓嶈繖涔堝仛锛岄氱敤瑙嗗浘灏变細鐢ㄤ互鍓嶇殑妯℃澘锛岃繖鍙兘涓嶆槸鎴戜滑鎯宠鐨勭粨鏋溿

Also notice that this isnt a very elegant way of doing publisher-specific books. If we want to add another publisher page, wed need another handful of lines in the URLconf, and more than a few publishers would get unreasonable. Well deal with this problem in the next section.

MM4VfH <a href=”http://xkukcvuspnqq.com/“>xkukcvuspnqq</a>, [url=http://hajkdanceogm.com/]hajkdanceogm[/url], [link=http://rqjewsqkkmjt.com/]rqjewsqkkmjt[/link], http://uhfoivgnfeiu.com/

Note

澶囨敞

If you get a 404 when requesting /books/apress/ , check to ensure you actually have a Publisher with the name Apress Publishing. Generic views have an allow_empty parameter for this case. See Appendix D for more details.

濡傛灉浣犲湪璇锋眰 /books/apress/ 鏃跺嚭鐜404閿欒锛岃妫鏌ヤ互纭繚浣犵殑鏁版嵁搴撲腑鍑虹増鍟 涓湁鍚嶄负Apress Publishing鐨勮褰曘傞氱敤瑙嗗浘鏈変竴涓 allow_empty 鍙傛暟鍙互 鐢ㄦ潵澶勭悊杩欎釜鎯呭喌锛岃鎯呰鐪嬮檮褰旸銆

Complex Filtering with Wrapper Functions

鐢ㄥ嚱鏁板寘瑁呮潵澶勭悊澶嶆潅鐨勬暟鎹繃婊

Another common need is to filter down the objects given in a list page by some key in the URL. Earlier we hard-coded the publishers name in the URLconf, but what if we wanted to write a view that displayed all the books by some arbitrary publisher? We can wrap the object_list generic view to avoid writing a lot of code by hand. As usual, well start by writing a URLconf:

yKnZxQ <a href=”http://bpzdrpbbjsjf.com/“>bpzdrpbbjsjf</a>, [url=http://cmholoypoxsv.com/]cmholoypoxsv[/url], [link=http://ihoiztkugwlg.com/]ihoiztkugwlg[/link], http://ozigifixmcgl.com/

urlpatterns = patterns('',
    (r'^publishers/$', list_detail.object_list, publisher_info),
    **(r'^books/(w+)/$', books_by_publisher),**
)

Next, well write the books_by_publisher view itself:

鎺ヤ笅鏉ワ紝鎴戜滑鍐 books_by_publisher 杩欎釜瑙嗗浘锛氾紙涓婇潰鐨勪唬鐮佷腑姝e垯琛ㄨ揪寮忔湁璇紝鍦 w 鍓嶈鍔犲弽鏂滅窔锛

from django.http import Http404
from django.views.generic import list_detail
from mysite.books.models import Book, Publisher

def books_by_publisher(request, name):

    # Look up the publisher (and raise a 404 if it can't be found).
    try:
        publisher = Publisher.objects.get(name__iexact=name)
    except Publisher.DoesNotExist:
        raise Http404

    # Use the object_list view for the heavy lifting.
    return list_detail.object_list(
        request,
        queryset = Book.objects.filter(publisher=publisher),
        template_name = "books/books_by_publisher.html",
        template_object_name = "books",
        extra_context = {"publisher" : publisher}
    )

This works because theres really nothing special about generic views theyre just Python functions. Like any view function, generic views expect a certain set of arguments and return HttpResponse objects. Thus, its incredibly easy to wrap a small function around a generic view that does additional work before (or after; see the next section) handing things off to the generic view.

杩欐槸鍥犱负閫氱敤瑙嗗浘灏辨槸Python鍑芥暟銆傚拰鍏朵粬鐨勮鍥惧嚱鏁颁竴鏍凤紝閫氱敤瑙嗗浘涔熸槸鎺ュ彈涓浜 鍙傛暟骞惰繑鍥 HttpResponse 瀵硅薄銆傚洜姝わ紝閫氳繃鍖呰閫氱敤瑙嗗浘鍑芥暟鍙互鍋氭洿澶氱殑浜嬨

Note

娉ㄦ剰

Notice that in the preceding example we passed the current publisher being displayed in the extra_context . This is usually a good idea in wrappers of this nature; it lets the template know which parent object is currently being browsed.

XGFs79 <a href=”http://orvtfnnzdtpg.com/“>orvtfnnzdtpg</a>, [url=http://bowbdcdfhptd.com/]bowbdcdfhptd[/url], [link=http://jjgdzbrfozjj.com/]jjgdzbrfozjj[/link], http://gnqujsbgtowe.com/

Performing Extra Work

澶勭悊棰濆宸ヤ綔

The last common pattern well look at involves doing some extra work before or after calling the generic view.

鎴戜滑鍐嶆潵鐪嬬湅鏈鍚庝竴涓父鐢ㄦā寮忥細鍦ㄨ皟鐢ㄩ氱敤瑙嗗浘鍓嶅悗鍋氫簺棰濆宸ヤ綔銆

Imagine we had a last_accessed field on our Author object that we were using to keep track of the last time anybody looked at that author. The generic object_detail view, of course, wouldnt know anything about this field, but once again we could easily write a custom view to keep that field updated.

鎯宠薄涓涓嬫垜浠湪 Author 瀵硅薄閲屾湁涓涓 last_accessed 瀛楁锛屾垜浠敤杩欎釜瀛楁鏉ユ洿姝eauthor鐨勬渶杩戣闂椂闂淬傚綋鐒堕氱敤瑙嗗浘 object_detail 骞朵笉鑳藉鐞 杩欎釜闂锛屾垜浠彲浠ュ緢瀹规槗鐨勫啓涓涓嚜瀹氫箟鐨勮鍥炬潵鏇存柊杩欎釜瀛楁銆

First, wed need to add an author detail bit in the URLconf to point to a custom view:

棣栧厛锛屾垜浠渶瑕佸湪URL閰嶇疆閲岃缃寚鍚戝埌鏂扮殑鑷畾涔夎鍥撅細

from mysite.books.views import author_detail

urlpatterns = patterns('',
    #...
    **(r'^authors/(?P<author_id>d+)/$', author_detail),**
)

Then wed write our wrapper function:

鎺ヤ笅鏉ュ啓鍖呰鍑芥暟锛

import datetime
from mysite.books.models import Author
from django.views.generic import list_detail
from django.shortcuts import get_object_or_404

def author_detail(request, author_id):
    # Look up the Author (and raise a 404 if she's not found)
    author = get_object_or_404(Author, pk=author_id)

    # Record the last accessed date
    author.last_accessed = datetime.datetime.now()
    author.save()

    # Show the detail page
    return list_detail.object_detail(
        request,
        queryset = Author.objects.all(),
        object_id = author_id,
    )

Note

娉ㄦ剰

This code wont actually work unless you add a last_accessed field to your Author model and create a books/author_detail.html template.

闄ら潪浣犳坊鍔 last_accessed 瀛楁鍒颁綘鐨 Author 妯″瀷骞跺垱寤 books/author_detail.html 妯℃澘锛屽惁鍒欒繖娈典唬鐮佷笉鑳界湡姝e伐浣溿

We can use a similar idiom to alter the response returned by the generic view. If we wanted to provide a downloadable plain-text version of the list of authors, we could use a view like this:

鎴戜滑鍙互鐢ㄥ悓鏍风殑鏂规硶淇敼閫氱敤瑙嗗浘鐨勮繑鍥炲笺傚鏋滄垜浠兂瑕佹彁渚涗竴涓緵涓嬭浇鐢ㄧ殑 绾枃鏈増鏈殑author鍒楄〃锛屾垜浠彲浠ョ敤涓嬮潰杩欎釜瑙嗗浘锛

def author_list_plaintext(request):
    response = list_detail.object_list(
        request,
        queryset = Author.objects.all(),
        mimetype = "text/plain",
        template_name = "books/author_list.txt"
    )
    response["Content-Disposition"] = "attachment; filename=authors.txt"
    return response

This works because the generic views return simple HttpResponse objects that can be treated like dictionaries to set HTTP headers. This Content-Disposition business, by the way, instructs the browser to download and save the page instead of displaying it in the browser.

杩欎釜鏂规硶涔嬫墍浠ュ伐浣滄槸鍥犱负閫氱敤瑙嗗浘杩斿洖鐨 HttpResponse 瀵硅薄鍙互璞′竴涓瓧鍏 涓鏍风殑璁剧疆HTTP鐨勫ご閮ㄣ傞殢渚胯涓涓嬶紝杩欎釜 Content-Disposition 鐨勫惈涔夋槸 鍛婅瘔娴忚鍣ㄤ笅杞藉苟淇濆瓨杩欎釜椤甸潰锛岃屼笉鏄湪娴忚鍣ㄤ腑鏄剧ず瀹冦

Whats Next?

涓嬩竴姝

In this chapter we looked at only a couple of the generic views Django ships with, but the general ideas presented here should apply pretty closely to any generic view. Appendix D covers all the available views in detail, and its recommended reading if you want to get the most out of this powerful feature.

鍦ㄨ繖涓绔犳垜浠彧璁蹭簡Django甯︾殑閫氱敤瑙嗗浘鍏朵腑涓閮ㄥ垎锛屼笉杩囪繖浜涙柟娉曚篃閫傜敤浜庡叾浠栫殑 閫氱敤瑙嗗浘銆傛湁鍏虫洿璇︾粏鐨勫唴瀹癸紝璇风湅闄勫綍D銆

In the next chapter we delve deep into the inner workings of Djangos templates, showing all the cool ways they can be extended. Until now, weve treated the template engine as a mostly static tool you can use to render your content.

鍦ㄤ笅涓绔犱腑鎴戜滑灏嗘繁鍏ュ埌Django妯℃澘绯荤粺鐨勫唴閮ㄥ幓锛屽睍绀烘墍鏈夋墿灞曞畠鐨勯叿鏂规硶銆傜洰鍓 涓烘锛屾垜浠繕鍙槸鎶婃ā鏉垮紩鎿庡綋浣滀竴涓覆鏌撳唴瀹圭殑闈欐佸伐鍏枫

Copyright 2006 Adrian Holovaty and Jacob Kaplan-Moss.
This work is licensed under the GNU Free Document License.
Hosting graciously provided by media temple
Chinese translate hosting by py3k.cn.