Django 2.0 path error ?: (2_0.W001) has a route that contains '(?P<', begins with a '^', or ends with a '$'

后端 未结 7 604
执念已碎
执念已碎 2020-12-08 08:59

I\'m new to Django and am trying to create the back end code for a music application on my website.

I have created the correct view in my views.py file (in the corre

相关标签:
7条回答
  • 2020-12-08 09:32

    Instead of using 're_path' you can also use ''(empty string) as the first argument of your path(). I have used it and it worked for me.

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('',views.index,name='index'),
    ]
    
    0 讨论(0)
  • 2020-12-08 09:36

    Use an empty string '' instead of '/' or r'^$'. It works like a charm. Code is as below:

    from django.urls import path, re_path
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', home, name='home'),
    ]
    
    0 讨论(0)
  • 2020-12-08 09:39

    url() is deprecated in newer version of django. So instead of using url use re_path() in your urls file as follows:

    from django.urls import path, re_path
    from . import views
    
    urlpatterns = [
        #url(r'^(?P<album_id>[0-9]+)/$', views.detail, name='detail'),
        path('', views.index, name='index'),
        re_path(r'^(?P<album_id>[0-9])/$', views.detail, name='detail'),
    ]
    
    0 讨论(0)
  • 2020-12-08 09:43

    The new path() syntax in Django 2.0 does not use regular expressions. You want something like:

    path('<int:album_id>/', views.detail, name='detail'),
    

    If you want to use a regular expression, you can use re_path().

    re_path(r'^(?P<album_id>[0-9])/$', views.detail, name='detail'),
    

    The old url() still works and is now an alias to re_path, but it is likely to be deprecated in future.

    url(r'^(?P<album_id>[0-9])/$', views.detail, name='detail'),
    
    0 讨论(0)
  • 2020-12-08 09:46

    In django 2.0 version primary key write this way...

    urls.py

    from django.urls import path
    
    from . import views
    
    
    urlpatterns = [
        path('', views.course_list),
        path('<int:pk>/', views.course_detail),
    ]
    
    0 讨论(0)
  • 2020-12-08 09:48

    Just to add to what @alasdair mentioned, I added re_path as part of the include and it works fine. Here is an example

    Add re_path to your import (for django 2.0)

    from django.urls import path, re_path
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        re_path(r'^$', home, name='home'),
    
    ]
    
    0 讨论(0)
提交回复
热议问题