Django NoReverseMatch at /qw-1/

后端 未结 2 1256
旧时难觅i
旧时难觅i 2021-01-15 17:43

Im new to django and was struck by using slug, now Im confused how to use the ID parameter and convert to slug

URL.py



        
2条回答
  •  别那么骄傲
    2021-01-15 18:38

    If you want to use both slug and id, your URL pattern should look like this:

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

    And your view should look like this:

    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)
    

    And your template also have to set both:

    {% csrf_token %}

提交回复
热议问题