阅读:2124次   评论:0条   更新时间:2011-06-01    

A shortcut: render_to_response()

快捷方法:render_to_response()

 

It's a very common idiom to load a template, fill a context and return an HttpResponse object with the result of the rendered template. Django provides a shortcut. Here's the full index() view, rewritten:

加载模板,传入context对象并返回一个包含了渲染后的模板内容的HttpResponse对象是一套连贯的操作。Django提供了快捷方法来一步完成这些工作。下面是重写过的index()方法:

from django.shortcuts import render_to_response

from mysite.polls.models import Poll

 

def index(request):

    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]

    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

 

Note that once we've done this in all these views, we no longer need to import loader, Context and HttpResponse.

注意一下一旦我们在视图中使用了这些方法,就没有必要再导入loadContextHttpResponse了。

 

The render_to_response() function takes a template name as its first argument and a dictionary as its optional second argument. It returns an HttpResponse object of the given template rendered with the given context.

render_to_response()方法接收模板名称作为第一参数,还可以接收一个字典作为可选的第二参数。改函数会根据传入的字典进行渲染模板,并返回HttpResponse对象。

 

Raising 404

抛出404异常

 

Now, let's tackle the poll detail view -- the page that displays the question for a given poll. Here's the view:

现在来看看这个视图——该页面会显示指定ID对应投票的问题。下面是全部代码:

from django.http import Http404

# ...

def detail(request, poll_id):

    try:

        p = Poll.objects.get(pk=poll_id)

    except Poll.DoesNotExist:

        raise Http404

    return render_to_response('polls/detail.html', {'poll': p})

 

The new concept here: The view raises the Http404 exception if a poll with the requested ID doesn't exist.

这里有个新的概念:如果根据ID找不到对应的数据,视图函数就会抛出一个Http404异常。

 

A shortcut: get_object_or_404()

快捷方法:get_object_or_404()

 

It's a very common idiom to use get() and raise Http404 if the object doesn't exist. Django provides a shortcut. Here's the detail() view, rewritten:

使用get()函数并判断是否抛出Http404错误是一套连贯的操作,因此Django提供了快捷方法。下面是重写过的detail()函数。

from django.shortcuts import render_to_response, get_object_or_404

# ...

def detail(request, poll_id):

    p = get_object_or_404(Poll, pk=poll_id)

    return render_to_response('polls/detail.html', {'poll': p})

 

The get_object_or_404() function takes a Django model module as its first argument and an arbitrary number of keyword arguments, which it passes to the module's get() function. It raises Http404 if the object doesn't exist.

get_object_or_404()函数接收一个Django模型作为第一参数,其他的关键字参数将传入到模型对象的get()方法中。如果查询不到任何结果时,将抛出http404异常。

 

Philosophy

Why do we use a helper function get_object_or_404() instead of automatically catching the ObjectDoesNotExist exceptions at a higher level, or having the model API raise Http404 instead of ObjectDoesNotExist?

Because that would couple the model layer to the view layer. One of the foremost design goals of Django is to maintain loose coupling.

哲学

为什么要用get_object_or_404()而不在更高级别上自动捕获ObjectDoesNotExist异常呢?为什么使用模型API来抛出http404异常而不是抛出ObjectDoesNotExist异常?

 

There's also a get_list_or_404() function, which works just as get_object_or_404() -- except using filter() instead of get(). It raises Http404 if the list is empty.

还有一个与get_object_or_404()方法一样的get_list_or_404()方法——只是对应的模型对象调用的是filter()不是get()方法。如果返回列表为空的话就会抛出Http404异常。

 

Write a 404 (page not found) view

编写404(找不到页面)视图

 

When you raise Http404 from within a view, Django will load a special view devoted to handling 404 errors. It finds it by looking for the variable handler404, which is a string in Python dotted syntax -- the same format the normal URLconf callbacks use. A 404 view itself has nothing special: It's just a normal view.

当视图里抛出一个Http404异常时,Django会加载一个专门用来处理这个异常的视图函数。

Django会根据变量handler404来查找这个视图,这个变量也是个Python包格式的字符串——和URLconf里面的回调函数的格式是一样的。404视图没有任何特别之处,它就只是个普通的视图而已。

 

You normally won't have to bother with writing 404 views. By default, URLconfs have the following line up top:

你不用太关注于怎样编写404视图。一般,URLconf设置里有下面的机制:

from django.conf.urls.defaults import *

 

That takes care of setting handler404 in the current module. As you can see in django/conf/urls/defaults.py, handler404 is set to django.views.defaults.page_not_found() by default.

这会将handler404导入到当前模块中。你可以在django/conf/urls/defaults.py中看到,handler404默认设置成了django.views.defaults.page_not_found()这个方法。

 

Three more things to note about 404 views:

  • The 404 view is also called if Django doesn't find a match after checking every regular expression in the URLconf.
  • If you don't define your own 404 view -- and simply use the default, which is recommended -- you still have one obligation: To create a 404.html template in the root of your template directory. The default 404 view will use that template for all 404 errors.
  • If DEBUG is set to True (in your settings module) then your 404 view will never be used, and the traceback will be displayed instead.

关于404视图还有三点要注意:

l         Django没有在URLconf设置中找到能够匹配当前URL的正则式时,也会调用404视图函数。

l         如果你没有自定义404视图——一般情况下会使用默认的——你还是要在模板目录下创建一个404.html文件。默认的404视图会为所有的404异常使用这个模板。

l         如果DEBUG设置为True(在settings模块里),404视图是永远都不会启用的,取而代之的是显示出追踪错误信息。

 

Write a 500 (server error) view

编写500视图(服务器错误)

 

Similarly, URLconfs may define a handler500, which points to a view to call in case of server errors. Server errors happen when you have runtime errors in view code.

类似于404错误,URLconf也可以定义一个handler500方法,在发生服务器错误时,这个方法会调用一个指定的视图。服务器错误是指在视图代码中产生的运行时错误。

 

Use the template system

使用模板

 

Back to the detail() view for our poll application. Given the context variable poll, here's what the "polls/detail.html" template might look like:

回来看看detail()视图函数。在给定了context变量——poll之后,现在的模板polls/detail.html看起来应该是这个样子:

<h1>{{ poll.question }}</h1>

<ul>

{% for choice in poll.choice_set.all %}

    <li>{{ choice.choice }}</li>

{% endfor %}

</ul>

 

The template system uses dot-lookup syntax to access variable attributes. In the example of {{ poll.question }}, first Django does a dictionary lookup on the object poll. Failing that, it tries attribute lookup -- which works, in this case. If attribute lookup had failed, it would've tried calling the method question() on the poll object.

模板系统使用“变量.属性”的方法来访问变量的属性值。在{{ poll.question }}这个例子中,Django先对poll做字典查询,不成功的话,就对进行属性查询——在这个例子属性查询成功了。如果属性查询也失败的话,会尝试调用poll对象的question()方法。

 

Method-calling happens in the {% for %} loop: poll.choice_set.all is interpreted as the Python code poll.choice_set.all(), which returns an iterable of Choice objects and is suitable for use in the {% for %} tag.

{% for %}循环中有方法调用:poll.choice_set.all会解释为Python方法poll.choice_set.all(),该方法会返回一组可迭代的Choice对象,可以用于{% for %}标签中。

 

See the template guide for more about templates.

请参考template_guide来了解模板的更多内容。

 

Simplifying the URLconfs

简化URLconf

 

Take some time to play around with the views and template system. As you edit the URLconf, you may notice there's a fair bit of redundancy in it:

花点时间再复习复习视图和模板吧。刚才你看过URLconf设置了,也许下面的代码看上去有点冗余:

urlpatterns = patterns('',

    (r'^polls/$', 'mysite.polls.views.index'),

    (r'^polls/(?P<poll_id>\d+)/$', 'mysite.polls.views.detail'),

    (r'^polls/(?P<poll_id>\d+)/results/$', 'mysite.polls.views.results'),

    (r'^polls/(?P<poll_id>\d+)/vote/$', 'mysite.polls.views.vote'),

)

 

Namely, mysite.polls.views is in every callback.

mysite.polls.views在这里重复出现了。

 

Because this is a common case, the URLconf framework provides a shortcut for common prefixes. You can factor out the common prefixes and add them as the first argument to patterns(), like so:

这是个很常见的情况,URLconf中可以对相同的方法前缀提供一个快捷方法。你可以把共同的方法前缀提取出来,将它作为patterns()的第一参数传入,就像下面这样:

urlpatterns = patterns('mysite.polls.views',

    (r'^polls/$', 'index'),

    (r'^polls/(?P<poll_id>\d+)/$', 'detail'),

    (r'^polls/(?P<poll_id>\d+)/results/$', 'results'),

    (r'^polls/(?P<poll_id>\d+)/vote/$', 'vote'),

)

 

This is functionally identical to the previous formatting. It's just a bit tidier.

这跟前面格式的功能是一样的。它只是变得简洁了一些。

 

Decoupling the URLconfs

解耦URLconf

 

While we're at it, we should take the time to decouple our poll-app URLs from our Django project configuration. Django apps are meant to be pluggable -- that is, each particular app should be transferable to another Django installation with minimal fuss.

现在应该把投票程序的URLDjango项目配置中解耦出来了。Django程序是插件式的——这意味着只要做很小的修改,它就可以转移到另外一个Django项目中。

 

Our poll app is pretty decoupled at this point, thanks to the strict directory structure that python manage.py startapp created, but one part of it is coupled to the Django settings: The URLconf.

现在这个投票程序已经基本上解耦了,这是由于python manage.py startapp所创建的目录结构有这严格的规范,但是还是有一部分还是耦合在这个项目中:就是URLconf

 

We've been editing the URLs in mysite/urls.py, but the URL design of an app is specific to the app, not to the Django installation -- so let's move the URLs within the app directory.

我们一直都是编辑mysite/urls.py里的URL设置,但是一个Django程序的URL设计应该由程序本身来规范,而不是在Django项目中规范——所以我们会在程序目录下面进行URL设置。

 

Copy the file mysite/urls.py to mysite/polls/urls.py. Then, change mysite/urls.py to remove the poll-specific URLs and insert an include():

mysite/urls.py拷贝到mysite/polls/urls.py。然后移除mysite/urls.py里和该程序有关的内容并插入一条include()函数,就像下面这样:

(r'^polls/', include('mysite.polls.urls')),

 

include(), simply, references another URLconf. Note that the regular expression doesn't have a $ (end-of-string match character) but has the trailing slash. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

include()函数就仅仅是引用了另外一个URLconf设置。注意一下上面的正则表达式中并没有$符号结尾,而只有一个斜杠结尾。当Django碰到include()函数时,会将URL中匹配到部分移除,并将剩下的URL字符串传入到对应的URLconf设置中做进一步的处理。

 

Here's what happens if a user goes to "/polls/34/" in this system:

  • Django will find the match at '^polls/'
  • Then, Django will strip off the matching text ("polls/") and send the remaining text -- "34/" -- to the 'mysite.polls.urls' URLconf for further processing.

现在看看匹配URL/polls/34/”的情况:

l         Django会找到匹配“^polls/”的部分。

l         然后,Django移除前面的“polls/”并将其余的部分“34/”传入到mysite.polls.urls中做进一步处理。

 

Now that we've decoupled that, we need to decouple the 'mysite.polls.urls' URLconf by removing the leading "polls/" from each line:

现在从每一行中移除前面的“polls/”,这样就完成了解耦:

urlpatterns = patterns('mysite.polls.views',

    (r'^$', 'index'),

    (r'^(?P<poll_id>\d+)/$', 'detail'),

    (r'^(?P<poll_id>\d+)/results/$', 'results'),

    (r'^(?P<poll_id>\d+)/vote/$', 'vote'),

)

 

The idea behind include() and URLconf decoupling is to make it easy to plug-and-play URLs. Now that polls are in their own URLconf, they can be placed under "/polls/", or under "/fun_polls/", or under "/content/polls/", or any other URL root, and the app will still work.

使用include()方法和URLconf解耦的初衷是为了方面做成即插即用式的URL。现在投票程序有自己独立的URLconf设置了,可以通过“/polls/”或者“/fun_polls/”甚至“/content/polls/

来访问它,程序始终都能正常运行。

 

All the poll app cares about is its relative URLs, not its absolute URLs.

投票程序关注的只是相对链接,不是绝对链接。

 

When you're comfortable with writing views, read part 4 of this tutorial to learn about simple form processing and generic views.

熟悉了视图之后,进入第四部分来学习一下表单处理和通用视图。

评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics