添加迁移后模板将不起作用

templates won't work after adding migrations

我通过迁移添加了数据,现在在 运行 migratemakemigrations 之后 我尝试 runserver 并且到处都是 NoReverseMatch 错误。

看看这个错误:

NoReverseMatch at /blog/

Reverse for 'blog_post_detail' with keyword
arguments '{'year': 2008, 'month': 9, 'slug': 'django-10-released'}'
not found. 1 pattern(s) tried:
['(?P<year>\d{4}/)^(?P<month>\d{1,2}/)^(?P<slug>\w+)/$']

在迁移中它看起来像这样:

POSTS = [
    {
        "title": "Django 1.0 Release",
        "slug": "django-10-released",
        "pub_date": date(2008, 9, 3),
        "startups": [],
        "tags": ["django", "python", "web"],
        "text": "THE Web Framework.",
    },]

这是实际的 url 模式:

    re_path (r'^(?P<year>\d{4}/)'
        r'^(?P<month>\d{1,2}/)'
        r'^(?P<slug>\w+)/$',post_detail,name='blog_post_detail'),

同样每个模板都有同样的问题....

^ 匹配字符串的开头,因此您不应该将它包含在正则表达式的中间。从 monthslug 字符串中删除它。您还应该将正斜杠移到命名组之外。如果您的 slug 包含连字符,那么您需要使用 [\w-]+ 而不是 \w+.

re_path (r'^(?P<year>\d{4})/'
    r'(?P<month>\d{1,2})/'
    r'(?P<slug>[\w-]+)/$',post_detail,name='blog_post_detail'),

就个人而言,我发现这个正则表达式在分成多行时更难。我更喜欢:

re_path (r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<slug>[\w-]+)/$',
         post_detail,name='blog_post_detail'),