NoReverseMatch at /posts/70/deletecomment/37/ Reverse for 'postdetail' with no arguments…
- User
NoReverseMatch at /posts/70/delete_comment/37/ Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['posts/(?P<post_id>[0-9]+)/\Z'] views: from django.db.models.base import Model as Model from django.db.models.query import QuerySet from django.utils import timezone from django.shortcuts import render, redirect, get_object_or_404 from blog.models import Post, Category, Comment from django.contrib.auth import login from django.contrib.auth.models import User from blogicum.settings import POST_PER_PAGE from .forms import ( CustomUserCreationForm, EditProfileForm, PostForm, CommentForm) from django.core.paginator import Paginator from django.views.generic import ( ListView, DetailView, UpdateView, CreateView, DeleteView) from django.urls import reverse_lazy, reverse from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin
def registration(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('index') else: form = CustomUserCreationForm() return render( request, 'registration/registration_form.html', {'form': form} )
def filtered_posts(post_id): return get_object_or_404( Post, id=post_id, is_published=True, pub_date__lte=timezone.now(), category__is_published=True, )
class PostListView(ListView): model = Post template_name = 'blog/index.html' paginate_by = POST_PER_PAGE context_object_name = 'posts'
codedef get_queryset(self): return Post.objects.filter( is_published=True, pub_date__lte=timezone.now(), category__is_published=True, ) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['add'] = True return contextdef post_detail(request, post_id): post = filtered_posts(post_id) form = CommentForm() comments = post.comments.all()
codeif request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.post = post comment.save() return redirect('blog:post_detail', post_id=post_id) context = { 'post': post, 'form': form, 'comments': comments, } return render(request, 'blog/detail.html', context) - Assistant
The error you're encountering,
NoReverseMatch at /posts/70/delete_comment/37/, is due to thesuccess_urlin yourDeleteCommentview. Thereverse_lazy('blog:post_detail')is being called without the necessary argumentpost_id, which causes the reverse lookup to fail sincepost_idis required for thepost_detailURL pattern.Solution
You need to pass the
post_idas a keyword argument when reversing the URL. Here’s how you can fix it:-
Update the
DeleteCommentview:Modify the
get_success_urlmethod in theDeleteCommentview to include the :
-