2016-03-18 8 views
1

イムDjangoのために新しいのとImが混乱してどのようにIDパラメータを使用してジャンゴ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を使用することができます。

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

そして、あなたのビューは次のようになります:あなたはスラグとidの両方を使用したい場合は、あなたのURLパターンは次のようになります参照 enter image description here

+0

[\ w-]を[ - \ w]に変更してみてください –

+1

「slug」と 'id'。あるいは、あなたが 'slug'か' id'のどちらかを受け入れるならば? –

答えて

4

私のオピオオンでは、idをslugに変換したくないです。 slugまたはidのいずれかで削除できるように、アプリケーションを十分に柔軟にすることができます。それに応じてパラメータを処理するだけで済みます。

だから、あなたはこのような何かを行うことができます。

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') 

とビューで

urls.py:あなたがに2つのURLパターンを圧縮することができます

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") 

注意単一のものですが、このアプローチは読みやすく理解しやすいものです。私はあなたがdjangoフレームワークなどに慣れたら、URLの統合を理解させます。

+1

テンプレートタグのURL名を更新する必要があると言えるでしょう: '{%url 'delete_post_by_id' id = post.id%}'。 – Alasdair

+0

ああ..絶対に右..ありがとう@Alasdair – karthikr

1

を事前に感謝し

エラー

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>