如何修复Django中的NoReverseMatch错误

时间:2018-08-13 08:18:02

标签: python django-rest-framework

我是django的新手,现在不知道该怎么办。我有这个错误:

  

在/ account / show-my-posts / 5 /

上的NoReverseMatch      

找不到带有参数'(15,5)'的'delete'的反向键。 1个图案   尝试过:['帐户/删除///']

我的观点(“ ShowMyPosts”和“ delete_post”):

class ShowMyPosts(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'show_my_posts.html'

    def get(self, request, pk, format=None):
        posts = Post.objects.all().filter(user=pk)
        serializerPosts = PostSerializer(posts,many=True)
        pprint.pprint(json.loads(JSONRenderer().render(serializerPosts.data))
        return Response({'posts': serializerPosts.data})


def delete_post(request,post_id=None,pk=None):
   post_to_delete = Post.objects.get(id=post_id)
   post_to_delete.delete()
   return HttpResponseRedirect('/account/show-my-posts/'  + pk + '/')

模板:

{% extends 'base2.html' %}
{% block content %}
<div class="container">



<div class="row">
    <div class="col-md-3 ">
         <div class="list-group ">
          <a href="{% url 'show_profile'  pk=user.id %}" class="list-group-item list-group-item-action">Profile</a>
          <a href="{% url 'show_my_posts'  pk=user.id %}" class="list-group-item list-group-item-action active">My Posts</a>


         </div>
    </div>

 <form method="post" action="" class="form-signin">
{% for post in posts %}
        <div id="cardme" style="padding:20px;margin-left:-100px">
         <div class="card text-center " style="width: 30rem;">
             <img class="card-img-top" src='{{post.profile_image}}' alt="Card image cap">
             <div class="card-body">
                 <h5 class="card-title">{{post.title}}</h5>
                 <h6 class="card-subtitle mb-2 text-muted">{{ post.created_date}}</h6>
                 <p class="card-text">{{post.text}}</p>
                 <a href="{% url 'delete' post.id  user.id %}"><button class="btn btn-primary">Delete</button></a>

             </div>
         </div>
        </div>
            {% endfor %}

 </form>


    </div>
</div>
{% endblock %}

URL:

url(r'show-my-posts/(?P<pk>[0-9]+)/', login_required(views.ShowMyPosts.as_view()), name='show_my_posts'),

 url(r'delete/<post_id>/<pk>/',views.delete_post,name='delete'),

1 个答案:

答案 0 :(得分:1)

您的网址有问题。当您要将变量传递给url时,应使用regex来实现。看一下这个例子:

url(r'^posts/(?P<id>\d+)/$', views.PostDetail.as_view(), name='post_detail')

此外,如果要使用常规方式,则应在此处指定数据类型:

path('posts/<int:id>/', views.PostDetail.as_view(), name='post_detail')

有关URL分配的更多信息,请参见this documentation