我有很多这样的通用模式:
urlpatterns = [
path('json/ay/<int:pk>', AyView.as_view(), name='json_ay'),
path('json/by/<int:pk>', ByView.as_view(), name='json_by'),
...
]
(当然,为了清楚起见,这些类不是简单的Ay
或By
),我正在尝试将它们转换为这样的通用函数:
first_cap_re = re.compile('(.)([A-Z][a-z]+)')
all_cap_re = re.compile('([a-z0-9])([A-Z])')
def convert(name):
s1 = first_cap_re.sub(r'\1_\2', name)
return all_cap_re.sub(r'\1_\2', s1).lower()
def json_view(view_class):
view_name = '_'.join(convert(view_class.__name__).split('_')[:-1])
return path(f'json/{view_name}/<int:pk>', view_class.as_view(),
name=f'json_{view_name}'),
然后这样称呼它:
urlpatterns = [
json_view(AyView),
json_view(ByView),
...
]
我收到此错误:
ERRORS:
?: (urls.E004) Your URL pattern (<URLPattern 'json/ay/<int:pk>' [name='json_ay']>,)
is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances.
HINT: Try using path() instead of a tuple.
我不知道为什么,知道吗?
答案 0 :(得分:1)
这只是return语句末尾的逗号,导致它返回一个元组。删除逗号。
line: "{{ item.path }}"