'HttpResponseRedirect Reverse not working Django
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 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |