对于Django 2.0,在urls.py中使用path()或url()更好吗? [英] Is it better to use path() or url() in urls.py for django 2.0?

查看:186
本文介绍了对于Django 2.0,在urls.py中使用path()或url()更好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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


url(regex,view,kwargs = None,name = None)此函数
django.urls.re_path()

url(regex, view, kwargs=None, name=None) This function is an alias to django.urls.re_path(). It’s likely to be deprecated in a future release.

路径 re_path 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()更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆