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

时间:2018-10-19 16:58:19

标签: python django python-3.x django-templates django-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.",
    },]

这是实际的urlpattern:

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

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

https://www.pinterest.co.uk/pin/402509285443188651/

1 个答案:

答案 0 :(得分:1)

^匹配字符串的开头,因此永远不要在正则表达式中间包含它。从monthslug字符串中删除它。您还应该将正斜杠移到命名组之外。如果您的标签中包含连字符,那么您需要使用[\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'),