问题描述
在django在线课程中,讲师让我们使用 url()
函数调用视图并使用urlpatterns列表中的正则表达式。我在youtube上看到了其他示例。
例如
In a django online course, the instructor has us use the url()
function to call views and utilize regular expressions in the urlpatterns list. I've seen other examples on youtube of this.e.g.
from django.contrib import admin
from django.urls import include
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^polls/', include('polls.urls')),
]
#and in polls/urls.py
urlpatterns = [
url(r'^$', views.index, name="index"),
]
但是,在阅读Django教程时,他们使用 path()
代替,例如:
However, in going through the Django tutorial, they use path()
instead e.g.:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name="index"),
]
此外,正则表达式似乎不适用于 path()
函数,因为使用 path(r'^ $',views.index,name = index)
找不到 mysite.com/polls /
视图。
Furthermore regular expressions don't seem to work with the path()
function as using a path(r'^$', views.index, name="index")
won't find the mysite.com/polls/
view.
是否使用了 path()
而没有正则表达式匹配正确的前进方式? url()
是否更强大但更复杂,因此他们使用 path()
开始学习吗?还是针对不同工作使用不同工具的情况?
Is using path()
without regex matching the proper way going forward? Is url()
more powerful but more complicated so they're using path()
to start us out with? Or is it a case of different tools for different jobs?
推荐答案
来自Django文档的
From Django documentation for url
和是 path
使用不带正则表达式的路由
Key difference between path
and re_path
is that path
uses route without regex
您可以将 re_path
用于复杂的正则表达式调用,而仅使用 path
用于更简单的查找
You can use re_path
for complex regex calls and use just path
for simpler lookups
这篇关于对于Django 2.0,在urls.py中使用path()或url()更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!