url()中的第三个参数名有什么用?为什么urlpatterns列表中只有一个元素却有逗号?

2024-03-28 15:47:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个django项目(教程),我在网址.py文件。你知道吗

from django.conf.urls import url
from . import views

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

我使用了这个文件并得到了正确的输出。但是,同样,为了进行实验,我从url函数中省略了“name”参数。只有两个参数,正则表达式和视图。像这样:

 from django.conf.urls import url
 from . import views

 urlpatterns = [
 url(r'^$', views.index),
 ]

尽管如此,我还是得到了正确的输出。 那么,为什么还有第三个参数,url函数中的name参数呢?你知道吗

另外,urlpatterns列表只包含1个元素,但是在关闭列表之前我们使用了“,”(逗号)。为什么?你知道吗


Tags: 文件项目django函数namefromimporturl
1条回答
网友
1楼 · 发布于 2024-03-28 15:47:48

why is there a third argument, the name parameter in the url function?

URL的name是这样的,您可以反转它,即获取特定视图的URL。例如,您可以在生成内部链接时使用它。你知道吗

the documentation

A common need when working on a Django project is the possibility to obtain URLs in their final forms either for embedding in generated content (views and assets URLs, URLs shown to the user, etc.) or for handling of the navigation flow on the server side (redirections, etc.)

The primary piece of information we have available to get a URL is an identification (e.g. the name) of the view in charge of handling it. Other pieces of information that necessarily must participate in the lookup of the right URL are the types (positional, keyword) and values of the view arguments.

让我们考虑一个例子:

假设你在建一个网站,你想做一个“关于我们”的页面。你也很喜欢恐龙,所以你会想,“如果我的网址都是恐龙的名字,那不是很酷吗?”所以你把这样的东西放到urls.py

url(r'^tyrannosaurus-rex$', views.about_us),

现在你想链接到那个页面,也许在你的导航栏里。没问题。您在模板中添加了这样的内容:

<a href="/tyrannosaurus-rex">About Us</a>

这是可行的,但是您复制了一些信息:您的“关于我们”页面可以在/tyrannosaurus-rex找到。你知道吗

由于某些原因,你的网站流量很小,所以你雇了人来研究你的搜索引擎优化。他们告诉你,你的网址真的应该与网页上的内容,而不是酷恐龙的名字。在这里,你的“关于我们”页面应该是/about-us。现在您必须返回并更新两个位置的代码:urls.py和您的模板。现在想象一下,为你的每一个链接都这样做。你知道吗

相反,如果你把

url(r'^tyrannosaurus-rex$', views.about_us, name='about_us'),

urls.py中,您可以使用the ^{} tag链接到它,如下所示:

<a href="{% url 'about_us' %}">About Us</a>

Django将查看您想要的URL的名称,并使用urls.py中的信息来确定链接应该指向什么。现在,当你改变你的链接结构时,你只需要做一次:在urls.py。因为链接的名称不变,{% url 'about_us' %}会自动生成一个新的、正确的链接。你知道吗

Also, the urlpatterns list contains only 1 element and yet we are using a ","(comma) before closing the list. Why is that?

列表中包含一个逗号,即使只有一个元素,因为它稍微简单一些。Python允许逗号,现在我们可以很容易地在逗号之前或之后添加条目,而不必更改它。你知道吗

相关问题 更多 >