2016-05-23 90 views
0

我向我的博客添加了一個編輯視圖,所以我的助理可以從前端編輯而不是管理區域。我的post_edit網址設置與我的post_detail相同,但最後的/edit/屬性除外。當我正在審閱帖子時,我手動將/edit/添加到URL的末尾,它很好用,但我遇到了一個問題,它創建了一個編輯按鈕並傳遞了參數。Django NoReverseMatch on post_edit URL

這是瀏覽器的錯誤:在/媒體/ 2016/05/23/gdfgdfcdcd/ 帶參數的反向關於 'post_edit' '(2016,5,23, 'gdfgdfcdcd')'

NoReverseMatch和關鍵字參數「{}」未找到。 1嘗試模式:['press /(?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

錯誤消息顯示正在使用'post_edit'模式...我假設它顯示'/ edit /'在最後。我只包含了兩個具有參數的url模式。 –

回答

1

你的正則表達式不匹配,因爲它期待這個月恰好是2位數字,但你只傳遞一個('5')。您應確保月份和日期參數均可接受一位或兩位數字。

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

每天學習新東西......謝謝! –

1

在網址你沒把{2}天的d月參數,這意味着你需要他們各自是兩個小數字符究竟是有效的這是不正確,所以最好將其更改爲{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'), 
    ... 
]