Django群组详情页提交评论表单时无法获取对应post_id的问题
Got it, let's fix this step by step. The core issue here is that your group detail page displays multiple posts, and each post needs its own comment form linked to its unique post_id. Right now you're only passing the first post to the form, which doesn't work for all posts in the group. Here's how to resolve this:
1. Fix the Group Detail View
First, clean up your groups/views.py detail function. You don't need to fetch a single post or pre-create a form for every post—instead, pass an empty comment form (since all posts use the same form structure) and the full list of posts in the group:
from django.shortcuts import get_object_or_404, render from .models import Group, Post from comments.forms import CommentForm # Import the comment form def detail(request, group_id): group = get_object_or_404(Group, pk=group_id) posts = Post.objects.filter(group__id=group_id) comment_form = CommentForm() # Create an empty comment form return render(request, 'groups/detail.html', { 'group': group, 'posts': posts, 'comment_form': comment_form })
Note: Your original code had a bug here—posts.objects.first() is invalid because posts is already a QuerySet. It should just be posts.first(), but we don't need this line at all anymore.
2. Update the Group Detail Template
In groups/detail.html, loop through each post in the group, and for each post, include the comment form while passing the current post object and the empty form to the included template:
<!-- groups/detail.html --> <h1>{{ group.name }}</h1> {% for post in posts %} <!-- Display post content --> <div class="post"> <h3>{{ post.title }}</h3> <p>{{ post.body }}</p> <!-- Include the comment form, passing the current post and empty form --> {% include "comments/comment_form.html" with post=post form=comment_form %} </div> {% endfor %}
3. Adjust the Comment Form Template
Make sure your comments/comment_form.html uses the passed post object to generate the correct action URL (so the form submits to the right create view with the post's ID):
<!-- comments/comment_form.html --> <h2>Add a comment to this post</h2> <form class="post-form" method="post" action="{% url 'comments:create' post.id %}"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save Comment</button> </form>
4. Verify the Comments URL Configuration
Double-check your comments/urls.py to ensure the create route accepts a post_id parameter—this is what makes {% url 'comments:create' post.id %} work:
# comments/urls.py app_name = 'comments' from django.urls import path from . import views urlpatterns = [ path('create/<int:post_id>/', views.create, name='create'), ]
5. (Optional) Clean Up the Create View's Redirect
Instead of hardcoding the redirect URL string, use Django's reverse function for better maintainability:
# comments/views.py from django.shortcuts import get_object_or_404, redirect, render from django.utils import timezone from django.urls import reverse # Add this import from .models import Comment, Post from .forms import CommentForm def create(request, post_id): post = get_object_or_404(Post, pk=post_id) group = post.group if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.post = post comment.pub_date = timezone.now() comment.save() # Use reverse to generate the group detail URL return redirect(reverse('groups:detail', args=[group.id])) else: form = CommentForm() return render(request, 'comments/comment_form.html', {'form': form, 'post': post})
This way, if you ever change your group detail URL pattern, you won't have to update this redirect code.
内容的提问来源于stack exchange,提问作者Nader

