Django评论表单提交后出现404页面未找到问题及AJAX改造需求
Let's break this down step by step—first we'll fix the 404 error, then convert the form to use AJAX for a smoother user experience.
1. Fixing the "Page not found" Error
Your main issue is the action attribute in your form tag. Right now you have <form action="POST">, which tells the browser to send the request to a path named /POST (which doesn't exist in your URLs). Here's how to fix it:
a. Correct the Form's Action URL
Replace the form tag with this, using Django's URL reverse resolution to point to the correct comment view:
<form action="{% url 'comment' pk=post.pk %}" method="POST" id="comment-form"> {% csrf_token %} {{ form.text.errors }} <label for="{{ form.text.id_for_label }}">comment:</label> {{ form.text }} <button id="comment" type="submit">comment</button> </form>
Note: Make sure post is available in your template context (it should be, since you're on a post detail page where comments are added).
b. Fix the View Logic for Saving Comments
Your current view has a bug when saving the comment—you're trying to assign post and writer to a comment variable that doesn't exist yet. You need to use commit=False to create the comment instance without saving it to the database first, then set the required fields, then save:
@login_required def comment(request, pk): if request.method == 'POST': form = CommentCreationForm(data=request.POST) if form.is_valid(): # Create comment instance without saving to DB yet comment = form.save(commit=False) # Assign the post and writer comment.post = get_object_or_404(Post, pk=pk) comment.writer = request.user # Now save to DB comment.save() messages.info(request, 'comment published') return JsonResponse({'message': 'Thank you for your comment'}, safe=False) else: form = CommentCreationForm() # If GET request or form invalid, return error response return JsonResponse({'error': 'Invalid request or form data'}, status=400)
2. Converting to AJAX Submission
To make the comment submit without reloading the page, we'll add vanilla JavaScript to handle the form submission asynchronously:
a. Add AJAX Handling Script
Add this script at the bottom of your HTML template (or in a separate JS file):
<script> const commentForm = document.getElementById('comment-form'); const commentInput = document.querySelector('#{{ form.text.id_for_label }}'); const messageContainer = document.createElement('div'); messageContainer.id = 'comment-feedback'; commentForm.parentNode.appendChild(messageContainer); commentForm.addEventListener('submit', async function(e) { e.preventDefault(); // Stop default page reload messageContainer.textContent = ''; const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value; const commentText = commentInput.value.trim(); if (!commentText) { messageContainer.textContent = 'Please enter a comment first'; messageContainer.style.color = 'red'; return; } try { const response = await fetch(commentForm.action, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': csrfToken }, body: `text=${encodeURIComponent(commentText)}` }); const data = await response.json(); if (response.ok) { messageContainer.textContent = data.message; messageContainer.style.color = 'green'; commentInput.value = ''; // Clear input after success // Optional: Add code here to refresh the comments list dynamically } else { messageContainer.textContent = `Error: ${data.error}`; messageContainer.style.color = 'red'; } } catch (error) { console.error('Submission failed:', error); messageContainer.textContent = 'Something went wrong. Please try again later.'; messageContainer.style.color = 'red'; } }); </script>
b. Optional: Polish User Feedback
The script above adds a dynamic feedback container to show success/error messages without using annoying alerts. You can style this container with CSS to match your site's design.
Quick Recap of Key Fixes
- Fixed the form's
actionattribute to use Django's URL reverse instead of the invalid "POST" path - Corrected the view to properly save comments by using
commit=Falsebefore assigning required fields - Added AJAX handling to submit comments without page reload, with dynamic user feedback
内容的提问来源于stack exchange,提问作者ketchup

