Django中提交评论后如何实现无页面刷新显示?
Hey there! Let's get that live comment update working for you. Since your comment already submits successfully but won't show up without a refresh, the issue is that your form is still using the default browser submit behavior (which reloads the page). We need to intercept that submission, send the data via AJAX, and then inject the new comment into your page manually.
Here's how to adjust your code step by step:
1. Update Your HTML First
First, let's add some IDs to make it easier to target elements with JavaScript, and wrap your existing comments in a container we can update:
<!-- Comment Input Area --> <form id='articleCommentForm' action="{% url 'submit_comment' %}"> {% csrf_token %} <textarea id="commentContent" placeholder='write comment'></textarea> <button type="submit">Comment</button> </form> <!-- Historical Comments Display Area (add a container ID) --> <div id="commentsList"> <!-- Your existing comments go here --> </div>
2. Add JavaScript to Handle AJAX Submission
Now we'll write a script to intercept the form submit, send the data without reloading, and add the new comment to the list using native JavaScript:
// Wait for the page to fully load document.addEventListener('DOMContentLoaded', function() { const commentForm = document.getElementById('articleCommentForm'); const commentsList = document.getElementById('commentsList'); const commentTextarea = document.getElementById('commentContent'); // Intercept form submission commentForm.addEventListener('submit', function(e) { // Prevent the default page refresh e.preventDefault(); // Get the CSRF token from the form (required for Django) const csrfToken = commentForm.querySelector('[name=csrfmiddlewaretoken]').value; const commentContent = commentTextarea.value.trim(); // Don't send empty comments if (!commentContent) return; // Send the comment via AJAX fetch(commentForm.action, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': csrfToken }, body: `csrfmiddlewaretoken=${csrfToken}&content=${encodeURIComponent(commentContent)}` }) .then(response => response.json()) // Assuming your backend returns JSON with comment data .then(data => { if (data.success) { // Add the new comment to the top of the comments list // If your backend returns pre-rendered HTML: commentsList.insertAdjacentHTML('afterbegin', data.comment_html); // OR build the HTML manually if you get raw data: // const newComment = document.createElement('div'); // newComment.className = 'comment-item'; // newComment.innerHTML = `<strong>${data.author}</strong>: <p>${data.content}</p>`; // commentsList.prepend(newComment); // Clear the textarea after successful submission commentTextarea.value = ''; } }) .catch(error => { console.error('Error submitting comment:', error); // Optionally show an error message to the user here }); }); });
3. Adjust Your Django Backend
Make sure your view handles the AJAX request properly—instead of redirecting, return a JSON response with the new comment's HTML or raw data:
from django.http import JsonResponse from django.template.loader import render_to_string def submit_comment(request): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save() # Render the comment to HTML using a partial template comment_html = render_to_string('partials/comment.html', {'comment': comment}) return JsonResponse({'success': True, 'comment_html': comment_html}) else: return JsonResponse({'success': False, 'errors': form.errors}) return JsonResponse({'success': False})
Quick Checks
- Ensure your form's
actionattribute points to your comment submission view (we added that in the HTML step) - The
X-CSRFTokenheader is non-negotiable for Django to accept the AJAX request - Style the new comment to match your existing ones so it blends in seamlessly
That should do it! Now when users submit a comment, it'll show up instantly without reloading the page.
内容的提问来源于stack exchange,提问作者Ahtisham

