简体   繁体   中英

Django: Change from using 'url' to 'path' in urls.py for this line (?P<hierarchy>.+)

I am using django2.0 and would like to convert the format of the urls.py from this to

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

urlpatterns = [
        url(r'^$',  views.post_list , name='post_list'),
        url(r'^(?P<slug>[\w-]+)/$', views.post_detail, name="detail"),
        url(r'^category/(?P<hierarchy>.+)/$', views.show_category, name='category'),
        ]

something similar to this:

from django.urls import path
from . import views

app_name='home'

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path(<slug:slug>/, views.post_detail, name="detail"),
    path(???),  
]

How should I code the last line in the new format. Thank you for any help rendered.

The documentation specifies five path converters: int , path , str , uuid , slug .

The regex pattern .+ means " matching one or more characters ", the characters can be anything. So a completely equivalent path converter is path :

path - Matches any non-empty string, including the path separator, '/' . This allows you to match against a complete URL path rather than just a segment of a URL path as with str .

So you can write it like:

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

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('<slug:slug>/', views.post_detail, name="detail"),
    path('category//', views.show_category, name='category'),
]

In case such hierarchy does not have to match slashes, then you can use str instead:

str - Matches any non-empty string, excluding the path separator, '/' . This is the default if a converter isn't included in the expression.

from django.urls import path
from . import views

app_name='home'

urlpatterns = [
    path('',  views.post_list , name='post_list'),
    path('<slug:slug>/', views.post_detail, name="detail"),
    path('category/<path:hierarchy>/', views.show_category, name='category'),
]

@Willem, thanks for guiding me to the answer. I still have much to learn and can only understand bits and pieces of the documentation, having no prior python programming background. The above code works for me.

@Don, I was trying to implement this https://github.com/djangopy-org/django_mptt_categories/blob/master/src/blog/urls.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM