【问题标题】:Django url path migration (1.11->3.1) warning for route symbols路由符号的 Django url 路径迁移 (1.11->3.1) 警告
【发布时间】:2021-04-16 08:46:20
【问题描述】:

从 1.11 迁移时,我在 Django 3.1.5 中收到此警告

?: (2_0.W001) Your URL pattern 'employee/attendanceactivity/attendance/(?P<attendance_id>\d+)/' [name='employee-attendanceactivity-detail'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path().

这是来自 url.py 的声明

path('employee/attendanceactivity/attendance/(?P<attendance_id>\d+)/', 
    views.employee_attendanceactivity_detail, name = 'employee-attendanceactivity-detail'), 

我应该如何解决这个警告?谢谢

【问题讨论】:

    标签: django-urls django-3


    【解决方案1】:

    从 Django 2.0 开始,re_path 应该用于匹配 URL 模式中的正则表达式。

    如下修改你的路径:

    from django.urls import re_path
    
    urlpatterns = [
        # ...
        re_path(r'^employee/attendanceactivity/attendance/(?P<attendance_id>\d+)/$', views.employee_attendanceactivity_detail, name = 'employee-attendanceactivity-detail'), 
        # ...
    ]
    
    

    参考。 Django URL 调度程序documentation

    【讨论】:

    • 你没有 ^ ?像这样 re_path(r'^.... 省略 ^ 有什么区别?@Awin
    • ^ 表示字符串的开头,$ 是字符串的结尾。没有它们,即使在字符串之间,它也会匹配re_path。更新了答案以包含 ^ 和 &
    • 如果我有这样的东西,我是否也将 $ 放在最后 --> re_path(r'^order/list/view_order/(?P\d+)', orderadmin_views .orderadmin_view_order, name='orderadmin_view_order'),
    • 是的,在最后添加 $ 会产生更具体的正则表达式。在您的情况下,如果没有 $,它也将匹配 order/list/view_order/123/some-string
    【解决方案2】:

    不幸的是,Stack 不允许我发表评论,但您后续问题的答案是,模式开头的 ^ 是 regex "start-of-line" anchor。虽然没有它您的路径可能会工作,但通常最好在 re_paths 的开头包含 ^ 并在结尾包含 $。

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 2021-12-03
      • 2019-09-21
      • 2020-11-11
      • 2019-07-17
      • 2021-12-14
      • 2020-07-12
      • 2016-10-25
      • 2018-01-04
      相关资源
      最近更新 更多