Overview

A view is a “type” of Web page in your Django application that generally serves a specific function and has a specific template. For example, in a blog application, you might have the following views:

  • Blog homepage – displays the latest few entries.
  • Entry “detail” page – permalink page for a single entry.
  • Year-based archive page – displays all months with entries in the given year.
  • Month-based archive page – displays all days with entries in the given month.
  • Day-based archive page – displays all entries in the given day.
  • Comment action – handles posting comments to a given entry.

In our poll application, we’ll have the following four views:

  • Question “index” page – displays the latest few questions.
  • Question “detail” page – displays a question text, with no results but with a form to vote.
  • Question “results” page – displays results for a particular question.
  • Vote action – handles voting for a particular choice in a particular question.

In Django, web pages and other content are delivered by views. Each view is represented by a simple Python function (or method, in the case of class-based views). Django will choose a view by examining the URL that’s requested (to be precise, the part of the URL after the domain name).

Now in your time on the web you may have come across such beauties as “ME2/Sites/dirmod.asp?sid=&type=gen&mod=Core+Pages&gid=A6CD4967199A42D9B65B1B”. You will be pleased to know that Django allows us much more elegant URL patterns than that.

A URL pattern is simply the general form of a URL - for example:/newsarchive/<year>/<month>/.

To get from a URL to a view, Django uses what are known as ‘URLconfs’. A URLconf maps URL patterns to views.

This tutorial provides basic instruction in the use of URLconfs, and you can refer to URL dispatcher for more information.

Writing more views

Now let’s add a few more views to polls/views.py. These views are slightly different, because they take an argument:

polls/views.py
 def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id) def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)

Wire these new views into the polls.urls module by adding the followingpath() calls:

polls/urls.py
from django.urls import path

from . import views

urlpatterns = [
# ex: /polls/
path('', views.index, name='index'),
# ex: /polls/5/
path('<int:question_id>/', views.detail, name='detail'),
# ex: /polls/5/results/
path('<int:question_id>/results/', views.results, name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),
]

Take a look in your browser, at “/polls/34/”. It’ll run the detail() method and display whatever ID you provide in the URL. Try “/polls/34/results/” and “/polls/34/vote/” too – these will display the placeholder results and voting pages.

When somebody requests a page from your website – say, “/polls/34/”, Django will load the mysite.urls Python module because it’s pointed to by theROOT_URLCONF setting. It finds the variable named urlpatterns and traverses the patterns in order. After finding the match at 'polls/', it strips off the matching text ("polls/") and sends the remaining text – "34/" – to the ‘polls.urls’ URLconf for further processing. There it matches '<int:question_id>/', resulting in a call to the detail() view like so:

detail(request=<HttpRequest object>, question_id=34)

The question_id=34 part comes from <int:question_id>. Using angle brackets “captures” part of the URL and sends it as a keyword argument to the view function. The :question_id> part of the string defines the name that will be used to identify the matched pattern, and the <int: part is a converter that determines what patterns should match this part of the URL path.

There’s no need to add URL cruft such as .html – unless you want to, in which case you can do something like this:

path('polls/latest.html', views.index),

But, don’t do that. It’s silly.

Write views that actually do something

Each view is responsible for doing one of two things: returning an HttpResponseobject containing the content for the requested page, or raising an exception such as Http404. The rest is up to you.

Your view can read records from a database, or not. It can use a template system such as Django’s – or a third-party Python template system – or not. It can generate a PDF file, output XML, create a ZIP file on the fly, anything you want, using whatever Python libraries you want.

All Django wants is that HttpResponse. Or an exception.

Because it’s convenient, let’s use Django’s own database API, which we covered in Tutorial 2. Here’s one stab at a new index() view, which displays the latest 5 poll questions in the system, separated by commas, according to publication date:

polls/views.py
from django.http import HttpResponse

from .models import Question

def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
output = ', '.join([q.question_text for q in latest_question_list])
return HttpResponse(output) # Leave the rest of the views (detail, results, vote) unchanged

There’s a problem here, though: the page’s design is hard-coded in the view. If you want to change the way the page looks, you’ll have to edit this Python code. So let’s use Django’s template system to separate the design from Python by creating a template that the view can use.

First, create a directory called templates in your polls directory. Django will look for templates in there.

Your project’s TEMPLATES setting describes how Django will load and render templates. The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a “templates” subdirectory in each of the INSTALLED_APPS.

Within the templates directory you have just created, create another directory called polls, and within that create a file called index.html. In other words, your template should be at polls/templates/polls/index.html. Because of how the app_directories template loader works as described above, you can refer to this template within Django simply as polls/index.html.

Template namespacing

Now we might be able to get away with putting our templates directly in polls/templates (rather than creating another pollssubdirectory), but it would actually be a bad idea. Django will choose the first template it finds whose name matches, and if you had a template with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the easiest way to ensure this is by namespacing them. That is, by putting those templates inside another directory named for the application itself.

Put the following code in that template:

polls/templates/polls/index.html
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}

Now let’s update our index view in polls/views.py to use the template:

polls/views.py
from django.http import HttpResponse
from django.template import loader from .models import Question def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))

That code loads the template called polls/index.html and passes it a context. The context is a dictionary mapping template variable names to Python objects.

Load the page by pointing your browser at “/polls/”, and you should see a bulleted-list containing the “What’s up” question from Tutorial 2. The link points to the question’s detail page.

A shortcut: render()

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

polls/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)

Note that once we’ve done this in all these views, we no longer need to importloader and HttpResponse (you’ll want to keep HttpResponse if you still have the stub methods for detailresults, and vote).

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

Raising a 404 error

Now, let’s tackle the question detail view – the page that displays the question text for a given poll. Here’s the view:

polls/views.py
from django.http import Http404
from django.shortcuts import render from .models import Question
# ...
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})

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

We’ll discuss what you could put in that polls/detail.html template a bit later, but if you’d like to quickly get the above example working, a file containing just:

polls/templates/polls/detail.html
{{ question }}

will get you started for now.

A shortcut: 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:

polls/views.py
from django.shortcuts import get_object_or_404, render

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

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

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 ofObjectDoesNotExist?

Because that would couple the model layer to the view layer. One of the foremost design goals of Django is to maintain loose coupling. Some controlled coupling is introduced in the django.shortcutsmodule.

There’s also a get_list_or_404() function, which works just as get_object_or_404() – except using filter() instead of get(). It raisesHttp404 if the list is empty.

Use the template system

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

polls/templates/polls/detail.html
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>

The template system uses dot-lookup syntax to access variable attributes. In the example of {{ question.question_text }}, first Django does a dictionary lookup on the object question. Failing that, it tries an attribute lookup – which works, in this case. If attribute lookup had failed, it would’ve tried a list-index lookup.

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

See the template guide for more about templates.

Removing hardcoded URLs in templates

Remember, when we wrote the link to a question in the polls/index.htmltemplate, the link was partially hardcoded like this:

<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>

The problem with this hardcoded, tightly-coupled approach is that it becomes challenging to change URLs on projects with a lot of templates. However, since you defined the name argument in the path() functions in the polls.urlsmodule, you can remove a reliance on specific URL paths defined in your url configurations by using the {% url %} template tag:

<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

The way this works is by looking up the URL definition as specified in thepolls.urls module. You can see exactly where the URL name of ‘detail’ is defined below:

...
# the 'name' value as called by the {% url %} template tag
path('<int:question_id>/', views.detail, name='detail'),
...

If you want to change the URL of the polls detail view to something else, perhaps to something like polls/specifics/12/ instead of doing it in the template (or templates) you would change it in polls/urls.py:

...
# added the word 'specifics'
path('specifics/<int:question_id>/', views.detail, name='detail'),
...

Namespacing URL names

The tutorial project has just one app, polls. In real Django projects, there might be five, ten, twenty apps or more. How does Django differentiate the URL names between them? For example, the polls app has a detail view, and so might an app on the same project that is for a blog. How does one make it so that Django knows which app view to create for a url when using the {% url %} template tag?

The answer is to add namespaces to your URLconf. In the polls/urls.py file, go ahead and add an app_name to set the application namespace:

polls/urls.py
from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]

Now change your polls/index.html template from:

polls/templates/polls/index.html
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

to point at the namespaced detail view:

polls/templates/polls/index.html
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>

Django 2.0 URL的更多相关文章

  1. Django 2.0 URL新版配置介绍

    实例 先看一个例子: from django.urls import path from . import views urlpatterns = [ path('articles/2003/', v ...

  2. Django 2.0 学习(02):Django视图和URL(上)

    接上篇博文,接下来我们以具体代码例子来说明Django的基本流程. 创建项目 使用Win+R,输入cmd进图windows命令行模式: 再你想要存放项目工作的磁盘,输入下面命令: django-adm ...

  3. django 2.0 中URL的include方法使用分析

    一.问题出现: 在使用Django2.0,配置全局URL时,希望指向某个APP的URL,配置如下: from django.contrib import admin from django.conf. ...

  4. Django < 2.0.8 任意URL跳转漏洞(CVE-2018-14574)

    影响版本 Django < 2.0.8 抓包 访问http://192.168.49.2:8000//www.example.com,即可返回是301跳转到//www.example.com

  5. python学习笔记--Django入门0 安装dangjo

    经过这几天的折腾,经历了Django的各种报错,翻译的内容虽然不错,但是与实际的版本有差别,会出现各种奇葩的错误.现在终于找到了解决方法:查看英文原版内容:http://djangobook.com/ ...

  6. Django 2.0 新特性 抢先看!

    一.Python兼容性 Django 2.0支持Python3.4.3.5和3.6.Django官方强烈推荐每个系列的最新版本. 最重要的是Django 2.0不再支持Python2! Django ...

  7. Django 之 路由URL,视图,模板,ORM操作

    1.后台管理的左侧菜单,默认只有第一个页签下面的选项是显示的,点了别的页签再显示别的页签下面的选项,问题是:点了任何菜单的选项后,左侧菜单又成了第一个页签的选项显示,别的页签隐藏,也就是左侧的菜单刷新 ...

  8. day73 Django框架之URL

    Django框架之url路由层一 Django数据库的一对多与多对多表的建立 一对多  publish_id的建立:publish=models.ForeignKey(to='Publish', to ...

  9. Django 2.0 学习

    Django django是基于MTV结构的WEB框架 Model 数据库操作 Template 模版文件 View 业务处理 在Python中安装django 2.0 1 直接安装 pip inst ...

随机推荐

  1. 关于Python 中的 if 语句

    学习Python,最开始我们都是先从函数学起,Python教程中有很多函数,if算是其中之一. 可能最为人所熟知的编程语句就是 if 语句了.例如: >>> >>> ...

  2. 传入中文参数-->服务器_转码的方法

    如果要传入 中文参数到 服务器 使用lr_convert_string_encoding()                            LR_ENC_SYSTEM_LOCALE ,  转为 ...

  3. [Clr via C#读书笔记]Cp16数组

    Cp16数组 一维数组,多维数组,交错数组:引用类型:P338的图非常的清楚地描述了值类型和引用类型在托管堆中的关系:越界检查: 数组初始化 数组初始化器: 四种写法 string[] names = ...

  4. 解读:未来30年新兴科技趋势报告(AI Frist,IoT Second)

    前段时间美国公布的一份长达35页的<未来30年新兴科技趋势报告>.该报告是在美国过去五年内由政府机构.咨询机构.智囊团.科研机构等发表的32份科技趋势相关研究调查报告的基础上提炼形成的. ...

  5. Java 集合框架之 Map

    Hashtable Hashtable 的实例有两个参数影响其性能:初始容量 和加载因子.容量 是哈希表中桶 的数量,初始容量就是哈希表创建时的容量.注意,哈希表的状态为 open:在发生“哈希冲突” ...

  6. lintcode-36-翻转链表 II

    36-翻转链表 II 翻转链表中第m个节点到第n个节点的部分 注意事项 m,n满足1 ≤ m ≤ n ≤ 链表长度 样例 给出链表1->2->3->4->5->null, ...

  7. iOS- iOS 和 Android 的后台推送原理各是什么?有什么区别?

    iOS 的推送iOS 在系统级别有一个推送服务程序使用 5223 端口.使用这个端口的协议源于 Jabber 后来发展为 XMPP ,被用于 Gtalk 等 IM 软件中.所以, iOS 的推送,可以 ...

  8. 3ds Max学习日记(二)

      搞了一天终于把第二章弄完了,虽然有点慢,但也是没有办法,毕竟中途学累了总得放松一下吧.   又get到了一个新知识点,是关于3ds max的捕捉工具的,详情见3DS MAX 学习笔记 一(捕捉工具 ...

  9. js设计模式之代理模式以及订阅发布模式

    为啥将两种模式放在一起呢?因为这样文章比较长啊. 写博客的目的我觉得首要目的是整理自己的知识点,进而优化个人所得知识体系.知识成为个人的知识,就在于能够用自己的话表达同一种意义. 本文是设计模式系列文 ...

  10. Dom的样式操作和属性操作

    如果说web的研究对象是html和css,那么整个dom结构,包含html树和dom树的dom结构才是研究对象,而在整个页面呈现上面,js起到的作用则是异步的用户行为. 按照上面整个思路,获取dom元 ...