据我了解,您有一个表单模式,r'(?P<group>pattern)?'
即您设置为可选的捕获组,在这种情况下,None
如果它不匹配任何内容,通常它会返回。
如果你真的想这样做而不是重构你的代码,你可以通过从源代码 [GitHub]复制来继承RegexPattern
和覆盖它:match
from django.urls.conf import _path
from django.urls.resolvers import RegexPattern
from functools import partial
class MyRegexPattern(RegexPattern):
def match(self, path):
match = self.regex.search(path)
if match:
# If there are any named groups, use those as kwargs, ignoring
# non-named groups. Otherwise, pass all non-named arguments as
# positional arguments.
kwargs = match.groupdict()
args = () if kwargs else match.groups()
# Commented line below from source code
# kwargs = {k: v for k, v in kwargs.items() if v is not None}
return path[match.end():], args, kwargs
return None
# Make the re_path function
re_path = partial(_path, Pattern=MyRegexPattern)
而不是使用这种解决方法,尽管更好的解决方案是指定多个 url 模式而不是一个,或者修复您的视图以允许这种情况。
假设你有这样的模式:
re_path(r'^prefix(?P<group>pattern)?suffix/$', views.some_view),
您可以编写两种模式,例如:
re_path(r'^prefix(?P<group>pattern)suffix/$', views.some_view),
re_path(r'^prefixsuffix/$', views.some_view, kwargs={'group': None}),
如果您以前有一个基于函数的视图,例如:
def some_view(request, group):
...
只需更改它,使组具有默认值None
:
def some_view(request, group=None):
...
如果在基于类的视图中您正在编写self.kwargs['group']
而不是编写self.kwargs.get('group')
.