我在博客中添加了一个编辑视图,因此我的助手可以从前端而不是管理区域进行编辑。我的post_edit
网址设置与我的post_detail
相同,但最后的/edit/
属性除外。当我查看帖子并手动将/edit/
添加到URL的末尾时,它运行良好,但我遇到了一个问题,即创建了一个编辑按钮并传递参数。
这是浏览器错误:
NoReverseMatch at / press / 2016/05/23 / gdfgdfcdcd / 使用参数'(2016,5,23,'gdfgdfcdcd')'和关键字参数'{}'找不到'post_edit'的反转。尝试了1种模式:['按/(?P \ d {4})/(?P \ d {2})/(?P \ d {2})/(?P [ - \ w] + )/编辑/ $']
感谢您的关注。
网址
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>
答案 0 :(得分:1)
在网址中,您确实为日期和月份参数添加了{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'),
...
]
答案 1 :(得分:1)
你的正则表达式不匹配,因为它预计月份恰好是2位数,但你只传递一个(&#39; 5&#39;)。您应该确保月和日参数都接受一位或两位数。
r'^press/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})...