4👍
✅
using
You can make use of the <path:…>
path converter [Django-doc], but this requires the element to be non-empty.
using re_path
If you thus want to match paths including empty ones, you can make use of the ([^/]+/)*
regex pattern:
from django.urls import re_path
urlpatterns = [
re_path(r'^business/(?P<path>([^/]+/)*)$', views.myview, name='myview'),
]
and then in the view split the path:
def myview(request, path):
path_items = path.split('/')
path_items
is than a list of path elements.
Custom path converter
You can also register a custom path converter:
# app/converters.py
class EmptyPathConverter:
regex = '([^/]+/)*'
def to_python(self, value):
return value.split('/')
def to_url(self, value):
return '/'.join(value)
and then register the path converter and use it when defining a path:
from app.converters import EmptyPathConverter
from django.urls import path, register_converter
register_converter(EmptyPathConverter, 'emptypath')
urlpatterns = [
path('business/<emptypath:paths>', views.myview, name='myview'),
]
then we can use this in a view, which will already do the splitting for us:
def myview(request, paths):
# paths is a list of strings
# …
Source:stackexchange.com