2016-03-18 51 views
1

進出口新的Django和被使用塞,現在林困惑如何使用ID參數,並轉換成團狀Django的NoReverseMatch在/ QW-1/

URL.py

url(r'^deletePost/(?P<slug>[\w-]+)/$', views.delete_post, name='delete_post') 
來襲

模板

<form method="POST" action="{% url 'delete_post' id=post.id %}">{% csrf_token %} 

    <button type="submit" class="btn btn-danger"> &nbsp Delete</button> 
</form> 

Views.py

def delete_post(request,slug): 
    posts=Post.objects.get(slug=slug) 
    if request.method == 'POST': 
     posts.delete() 
     return redirect("home") 

如何使用塞& ID刪除其中創建

任何幫助表示讚賞後。在此先感謝

錯誤參考 enter image description here

+0

嘗試改變[\ w-]到[ - \ w] –

+1

目前還不清楚你是否需要'slug'和'id'。或者,如果你接受'slug'或'id'? –

回答

4

在我的opionion中,你不想將ID轉換爲slu。。您可以使您的應用程序足夠靈活,以便您可以通過slugid刪除。你只需要相應地處理參數。

所以,你可以做這樣的事情:

urls.py

url(r'^deletePost/(?P<slug>[\w-]+)/$', views.delete_post, name='delete_post_by_slug'), 
url(r'^deletePost/(?P<id>[0-9]+)/$', views.delete_post, name='delete_post_by_id') 

而且在訪問量:

def delete_post(request, slug=None, id=None): 
    if slug: 
     posts=Post.objects.get(slug=slug) 
    if id: 
     posts=Post.objects.get(id=id) 
    #Now, your urls.py would ensure that this view code is executed only when slug or id is specified 

    #You might also want to check for permissions, etc.. before deleting it - example who created the Post, and who can delete it. 
    if request.method == 'POST': 
     posts.delete() 
     return redirect("home") 

請注意,您可以壓縮2種URL模式成單一的 - 但這種方法保持它的可讀性和可理解性。當你對django框架感到滿意時,我會讓你弄清楚URL合併。

+1

可能值得一提的是,您需要更新模板標記中的網址名稱:'{%url'delete_post_by_id'id = post.id%}'。 – Alasdair

+0

啊..絕對正確..謝謝@Alasdair – karthikr

1

如果你想同時使用廢料和ID,你的URL模式應該是這樣的:

url(r'^deletePost/(?P<slug>[\w-]+)-(?P<id>[0-9]+)/$', 
    views.delete_post, name='delete_post') 

而且您認爲應該是這樣的:

def delete_post(request, **kwargs): 
    # Here kwargs value is {'slug': 'qw', 'id': '1'} 
    posts = Post.objects.get(**kwargs) 
    if request.method == 'POST': 
     posts.delete() 
     return redirect('home') 
    # ... (I guess this view does not end here) 

而你的模板也必須設置兩個:

<form method="POST" action="{% url 'delete_post' slug=post.id id=post.id %}">{% csrf_token %} 

    <button type="submit" class="btn btn-danger"> &nbsp Delete</button> 
</form>