您的位置:首页 > 编程语言 > Go语言

Django 1.7 初级教程or学习笔记(四)

2014-10-15 08:02 513 查看
在写这个的时候,会发现,表达有时候非常的不准确,慢慢来吧。。。

还有,发现了一个好多西,Django1.5中文手册(URL:http://django-chinese-docs.readthedocs.org/en/latest/)虽然版本有变化,代码也不同,但是在看官方的英文文档的解释的时候,不明白什么意思的话,就可以对比这看一下,很多地方都是一样的~非常赞~

------------------------------------------------START-------------------------------------------------

视图

视图是Django 应用程序中的包含特定的功能而且有特定的模板的一"类"的网页。

每一个视图就是一个简单的Python函数或者方法来表达,Django 通过检查请求的URL中来匹配(map)一个视图,准确的说,是通过检测域名之后的URL来选择视图。

Django通过一个名为“URLconfs”的机制将 URL模式(正则表达式匹配)映射到视图上,并且获得视图。

编写第一个视图:

打开 polls/views.py 文件,并且输入以下代码:

from django.http import HttpResponse

def index(request):

return HttpResponse("Hello, world. You're at the polls index.")

这是最简单的视图,如果要调用这个视图,我们需要通过URLconf将其映射到一个URL上,所以接下来,在polls 目录下创建URLconf,创建一个名为 urls.py的文件,你的app的目录结构应该是长成这个样子的:

polls/

__init__.py

admin.py

models.py

tests.py

urls.py

views.py

创建好urls.py 文件之后,在文件中创建一个url()方法,将视图和URL匹配上,输入以下代码:

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns( '',

url(r'^$', views.index, name='index'),

)

现在做的这些,在polls app 内部解决了 URL到视图的映射,现在要让mysite知道,所以将 polls.urls 模块指向 root URLconf 。在 mysite/urls.py 中插入一个 include() 方法,代码如下:

from django.conf.urls import patterns, include, url

from django.contrib import admin

urlpatterns = patterns('',

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

url(r'^admin/', include(admin.site.urls)),

)

现在你在 URLconf 中配置了 index 视图。通过浏览器访问 http://localhost:8000/polls/ ,如同你在 index 视图中定义的一样,你将看到 “Hello, world. You’re at the poll index.” 文字。

编写更多的视图:

我们开始在 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)

接下来,将这些新定义的视图通过URLconf将其映射到一个URL上,在polls/urls.py中添加新的url()方法,代码如下:

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',

# ex: /polls/

url(r'^$', views.index, name='index'),

# ex: /polls/5/

url(r'^(?P<question_id>\d+)/$', views.detail, name='detail'),

# ex: /polls/5/results/

url(r'^(?P<question_id>\d+)/results/$', views.results, name='results'),

# ex: /polls/5/vote/

url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),

)

在你的浏览器中访问 http://localhost:8000/polls/34/ 。将运行 detail() 方法并且显示你在 URL 中提供的任意 ID 。试着访问 http://localhost:8000/polls/34/results/http://localhost:8000/polls/34/vote/ – 将会显示对应的结果页及投票页。

在视图中添加实际的功能:

每一个视图只负责以下的两件事情之一:1.返回一个 HttpResponse 对象,包含请求的页面。2.抛出一个异常,例如 Http404 。除此之外,你可以用他来读取数据库记录,生成PDF文件,输出XML文件,展开你丰富的联想~

因为它很方便,我们直接使用 Django 自己的数据库 API 。修改下 index() 视图, 让它显示系统中最新发布的 5 个调查问题,以逗号分割并按发布日期排序,在polls/views.py中,修改以下,代码如下:

from django.http import HttpResponse

from polls.models import Question

def index(request):

latest_question_list = Question.objects.order_by('-pub_date')[:5]

output = ', '.join([p.question_text for p in latest_question_list])

return HttpResponse(output)

# Leave the rest of the views (detail, results, vote) unchanged

这样会有一个问题,index方法直接返回了一个页面,(叫做将页面设计硬编码进视图),假如说,我们要修改一下页面设计,就必须修改这里的代码,这样很麻烦。所以将页面设计从Python代码中分离出来。

首先,在 polls 目录下创建一个 templates 目录。 Django 将会在那寻找模板。(默认的)。刚才创建的``templates`` 目录下,另外创建个名为 polls 的目录,并在其中创建一个 index.html 文件。换句话说,你的模板路径应该是 polls/templates/polls/index.html 。

在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 %}

更新一下 polls/views.py ,代码如下:

from django.http import HttpResponse

from django.template import RequestContext, loader

from polls.models import Question

def index(request):

latest_question_list = Question.objects.order_by('-pub_date')[:5]

template = loader.get_template('polls/index.html')

context = RequestContext(request, {

'latest_question_list': latest_question_list,

})

return HttpResponse(template.render(context))

代码将加载 polls/index.html 模板并传递一个 context 变量。

在你的浏览器中加载 “/polls/” 页,你应该看到一个列表,包含了在教程 第1部分 中创建的 “What’s up” 调查。而链接指向 poll 的详细页面。

快捷方式:render()

这是一个非常常见的习惯用语,用于加载模板,填充上下文并返回一个含有模板渲染结果的 HttpResponse 对象。 Django 提供了一种快捷方式。这里重写完整的 index() 视图,在polls/views.py中,代码如下:

from django.shortcuts import render

from polls.models import Question

def index(request):

latest_question_list = Question.objects.all().order_by('-pub_date')[:5]

context = {'latest_question_list': latest_question_list}

return render(request, 'polls/index.html', context)

render() 函数中第一个参数是 request 对象,第二个参数是一个模板名称,第三个是一个字典类型的可选参数。 它将返回一个包含有给定模板根据给定的上下文渲染结果的 HttpResponse 对象。

抛出404异常:

现在,处理一下视图,polls/views.py,代码如下:

from django.http import Http404

from django.shortcuts import render

from polls.models import Question

# ...

def detail(request, question_id):

try:

question = Question.objects.get(pk=question_id)

except Question.DoesNotExist:

raise Http404

return render(request, 'polls/detail.html', {'question': question})

当请求的question ID 不存在的时候,会抛出一个 Http404 异常,想要快速的检测一下上面的代码的作用,在模板文件中,路径为:polls/templates/polls/detail.html

代码如下:

{{ question }}

加载浏览器。。。。。。

快捷方式: get_object_or_404()

当你使用 get() 获取对象, 对象却不存在时就会抛出 Http404 异常。对此 Django 提供了一个快捷操作。如下所示重写 detail() 视图,代码如下(路径:

polls/views.py):

from django.shortcuts import get_object_or_404, render

from polls.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})

使用模板系统

回到我们 poll 应用的 detail() 视图中,指定 poll 变量后,``polls/detail.html`` 模板可能看起来这样(路径:

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>

移除模板中硬编码的 URLS

在模板 polls/index.html 中,链接到 poll 的链接是成这样子的:

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

如果要修改URL变成一个非常麻烦的事情,所以换一种方式来表达。

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

URL 名称的命名空间

到现在,项目只有一个应用:``polls`` 。在实际的 Django 项目中,一定会有 更多的应用。这样Django 需要区分不同的URL名称。

在 root URLconf 配置中添加命名空间。在 mysite/urls.py 文件 (项目的 ``urls.py``,不是应用的) 中,修改为包含命名空间的定义(路径:mysite/urls.py):

from django.conf.urls import patterns, include, url

from django.contrib import admin

urlpatterns = patterns('',

url(r'^polls/', include('polls.urls', namespace="polls")),

url(r'^admin/', include(admin.site.urls)),

)

现在将你的 polls/index.html 模板中原来的 detail 视图(路径:polls/templates/polls/index.html):

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

修改为包含命名空间的 detail 视图:

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

---------------------------------------------------------------------------------------------------------------------------------

更多细节,查阅官方文档,此部分链接:https://docs.djangoproject.com/en/1.7/intro/tutorial03/

到这里,本部分结束。不过~要加快一点了~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: