【问题标题】:Django NoReverseMatch on post_edit URLpost_edit URL 上的 Django NoReverseMatch
【发布时间】:2016-05-23 17:19:21
【问题描述】:

我向我的博客添加了一个编辑视图,以便我的助手可以从前端而不是管理区域进行编辑。我的post_edit URL 设置与我的post_detail 相同,除了末尾的/edit/ 属性。当我查看帖子并手动将/edit/ 添加到 URL 的末尾时,效果很好,但是我在创建编辑按钮和传递参数时遇到了问题。

这是浏览器错误:

NoReverseMatch 在 /press/2016/05/23/gdfgdfcdcd/ 使用参数 '(2016, 5, 23, 'gdfgdfcdcd')' 和关键字参数 '{}' 未找到的 'post_edit' 反向。尝试了 1 种模式:['press/(?P\d{4})/(?P\d{2})/(?P\d{2})/(?P[-\w]+ )/edit/$']

感谢您的关注。

网址

urlpatterns = [
    ...
    url(r'^press/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'),
    url(r'^press/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/edit/$', views.post_edit, name='post_edit'),
    ...
]

查看

def post_edit(request, year, month, day, post):
    post = get_object_or_404(Post, slug=post, status='published', created__year=year, created__month=month, created__day=day)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            form.save()
            form.save_m2m()
            return HttpResponseRedirect(post.get_absolute_url())
    else:
        form = PostForm(instance=post)
    return render(request, 'press/post_edit.html', {'post': post, 'form': form})

模板

<a href="{% url 'press:post_edit' post.created.year post.created.month post.created.day post.slug %}"><i class="fa fa-envelope-o" aria-hidden="true"></i> Edit Post</a>

【问题讨论】:

  • 错误消息显示正在使用post_edit 模式...我假设因为它在末尾显示/edit/。我包含了仅有的两个具有参数的 url 模式。

标签: django django-forms django-templates django-views


【解决方案1】:

您的正则表达式不匹配,因为它期望该月正好有 2 位数字,但您只传递了一位 ('5')。您应该确保月份和日期参数都接受一位或两位数字。

r'^press/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})...

【讨论】:

    【解决方案2】:

    在您确实将 {2} 用于日期和月份参数的网址中,这意味着您需要它们每个都是两个十进制字符才能完全有效,这是不正确的,因此最好将其更改为 {1,2}:

    urlpatterns = [
        ...
        url(r'^press/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'),
        url(r'^press/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<post>[-\w]+)/edit/$', views.post_edit, name='post_edit'),
        ...
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-26
      • 2013-01-19
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      • 2019-07-15
      • 2017-03-14
      • 2016-06-04
      相关资源
      最近更新 更多