编写你的第一个 Django 应用,第 1 部分 |
您所在的位置:网站首页 › 简单的app开发案例文档 › 编写你的第一个 Django 应用,第 1 部分 |
编写第一个视图¶
让我们开始编写第一个视图吧。打开 polls/views.py,把下面这些 Python 代码输入进去: polls/views.py¶ from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.")This is the most basic view possible in Django. To access it in a browser, we need to map it to a URL - and for this we need to define a URL configuration, or "URLconf" for short. These URL configurations are defined inside each Django app, and they are Python files named urls.py. To define a URLconf for the polls app, create a file polls/urls.py with the following content: polls/urls.py¶ from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ]Your app directory should now look like: polls/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py urls.py views.pyThe next step is to configure the global URLconf in the mysite project to include the URLconf defined in polls.urls. To do this, add an import for django.urls.include in mysite/urls.py and insert an include() in the urlpatterns list, so you have: mysite/urls.py¶ from django.contrib import admin from django.urls import include, path urlpatterns = [ path("polls/", include("polls.urls")), path("admin/", admin.site.urls), ]函数 include() 允许引用其它 URLconfs。每当 Django 遇到 include() 时,它会截断与此项匹配的 URL 的部分,并将剩余的字符串发送到 URLconf 以供进一步处理。 我们设计 include() 的理念是使其可以即插即用。因为投票应用有它自己的 URLconf( polls/urls.py ),他们能够被放在 "/polls/" , "/fun_polls/" ,"/content/polls/",或者其他任何路径下,这个应用都能够正常工作。 何时使用 include() 当包括其它 URL 模式时你应该总是使用 include() , admin.site.urls 是唯一例外。 你现在把 index 视图添加进了 URLconf。通过以下命令验证是否正常工作: $ python manage.py runserver ...\> py manage.py runserver用你的浏览器访问 http://localhost:8000/polls/,你应该能够看见 "Hello, world. You're at the polls index." ,这是你在 index 视图中定义的。 没有找到页面? 如果你在这里得到了一个错误页面,检查一下你是不是正访问着http://localhost:8000/polls/ 而不应该是 http://localhost:8000/。 函数 path() 具有四个参数,两个必须参数:route 和 view,两个可选参数:kwargs 和 name。现在,是时候来研究这些参数的含义了。 path() 参数: route¶route 是一个匹配 URL 的准则(类似正则表达式)。当 Django 响应一个请求时,它会从 urlpatterns 的第一项开始,按顺序依次匹配列表中的项,直到找到匹配的项。 这些准则不会匹配 GET 和 POST 参数或域名。例如,URLconf 在处理请求 https://www.example.com/myapp/ 时,它会尝试匹配 myapp/ 。处理请求 https://www.example.com/myapp/?page=3 时,也只会尝试匹配 myapp/。 path() 参数: view¶当 Django 找到了一个匹配的准则,就会调用这个特定的视图函数,并传入一个 HttpRequest 对象作为第一个参数,被“捕获”的参数以关键字参数的形式传入。稍后,我们会给出一个例子。 path() 参数: kwargs¶任意个关键字参数可以作为一个字典传递给目标视图函数。本教程中不会使用这一特性。 path() 参数: name¶为你的 URL 取名能使你在 Django 的任意地方唯一地引用它,尤其是在模板中。这个有用的特性允许你只改一个文件就能全局地修改某个 URL 模式。 当你了解了基本的请求和响应流程后,请阅读 教程的第 2 部分 开始使用数据库. |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |