HttpResponseRedirect Reverse not working Django

Issue

I am trying to redirect my page after submitting a like button to the same page but I keep getting a

NoReverseMatch at /score/like/2

Here is the urls

urlpatterns = [
    path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
    path('', PostListView.as_view(), name='score'),
    path('<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('like/<int:pk>', LikeView, name='like_post'),

Here is the views

def LikeView(request, pk):
    post = get_object_or_404(Post, id=request.POST.get('post_id'))
    post.likes.add(request.user)
    return HttpResponseRedirect(reverse('post-detail', args=[str(pk)])) <-----Error highlighting here

here is the templates

                        <form action="{% url 'score:like_post' post.pk %}" method='POST'>
                            {% csrf_token %}
                                <button type='submit' name='post_id' class= "btn btn-primary btn-sm" value="{{post.id}}"> Like </button>                            
                        </form>                        
                        <strong>{{post.total_liked}} Likes </strong>

Solution

Given the template your urls.py specify an app_name. You need to use that as prefix in the name of the view.

Furthermore you can make use of redirect(…) [Django-doc] which calls reverse and wraps the result in a HttpResponseRedirect (so it removes some boilerplate):

from django.shortcuts import redirect

def LikeView(request, pk):
    post = get_object_or_404(Post, id=request.POST.get('post_id'))
    post.likes.add(request.user)
    return redirect('score:post-detail', pk=pk)

Answered By – Willem Van Onsem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published