1

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.

moonfairy
  • 75
  • 3
  • 14
  • in the future provide more information. We do not know what the expected value of `hierarchy` which is needed to know how to properly convert this url. – Don Aug 22 '18 at 14:35

2 Answers2

2

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/<path:hierarchy>/', 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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0
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

moonfairy
  • 75
  • 3
  • 14