Django文档学习

应用程序为polls; 项目为mysite

为了调用view,需要将他映射到URL,为了做到这个我们需要一个URLconf

在polls目录中创建URLconf:创建一个名为urls.py的文件,包含以下代码:

# polls/urls.py

from django.http import HttpResponse


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

 下一步将根URLconf指向polls.urls模块:在mysite/urls.py中添加导入django.urls.include并将一个include()插入到urlpatterns列表:

# 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()函数允许引用其他URLconf。每当Django遇到时include(),它都会删除与该点匹配的URL的任何部分,并将剩余的字符串发送到包含的URLconf以进行进一步处理。

背后的想法include()是使即插即用的URL变得容易。由于民意调查位于他们自己的URLconf(polls/urls.py)中,因此可以将它们放在“/ polls /”下,或“/ fun_polls /”下,或“/ content / polls /”下,或任何其他路径根目录下,并且应用仍会工作。

(英文原文:

The include() function allows referencing other URLconfs. 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.

The idea behind include() is to make it easy to plug-and-play URLs. Since polls are in their own URLconf (polls/urls.py), they can be placed under “/polls/”, or under “/fun_polls/”, or under “/content/polls/”, or any other path root, and the app will still work.

什么时候用include()?

include()当你包含其他URL模式(pattern)时,应始终使用。admin.site.urls是唯一的例外。

 该path()函数传递了四个参数,两个必需: routeview,以及两个可选:kwargs,和name。在这一点上,值得回顾一下这些论点的用途:

route是包含URL模式的字符串。处理请求时,Django从第一个模式开始urlpatterns并沿着列表向下移动,将请求的URL与每个模式进行比较,直到找到匹配的模式。

模式不搜索GET和POST参数或域名。

例如,在请求中https://www.example.com/myapp/,URLconf将查找 myapp/。在请求中https://www.example.com/myapp/?page=3,URLconf也会查找myapp/

当Django找到匹配的模式时,它调用指定的视图函数,其中一个HttpRequest对象作为第一个参数,并且路由中的任何“捕获”值作为关键字参数。

  • path()参数:kwargs:任意关键字参数可以在字典中传递到目标视图

  • path()参数:name:命名您的URL可让您从Django的其他地方明确地引用它,尤其是在模板中。此强大功能允许您在仅触摸单个文件的同时对项目的URL模式进行全局更改。

链接:https://docs.djangoproject.com/en/2.1/intro/tutorial01/​​​​​​​

猜你喜欢

转载自blog.csdn.net/Keruila/article/details/82430045
今日推荐