skip to Main Content

So i am building a blog with Django and I am trying to implement a comment functionality with JQuery to avoid a page refresh. I’ve written the codes but when I click on the comment submit button, I get sent to a white page with JSON data. I’ve struggled with this problem for too long and i’m hoping for a solution here. Following are the relevant codes.

in my detail page, this is the html for the comment form:

<div id="comment-container" class="comment-container" style="display: none;">
                      <form id="comment-form" method="post" action="{% url 'article:comment_submit' post.slug %}">
                        {% csrf_token %}
                        <textarea id="comment-textarea"
                        style="font-size: 16px; color: #333; background-color: #f2f2f2; border: 1px solid #ccc; 
                        border-radius: 4px; padding: 8px; outline: none; text-align:left;" name="comment" rows="4" cols="50">
                        </textarea>
                        <button id="submit-comment" style="display: block;" type="button">Submit</button>
                      </form>
                    </div>

still in my detail page is an empty div tag where I intend to prepend/append the comments:

<div id="comments-section">
                    </div>
                

in my main.js, I have:

$(document).ready(function() {
    // Function to submit the comment form using AJAX
    $("#submit-comment").on("click", function(event) {
      event.preventDefault()
      var commentText = $("#comment-textarea").val().trim();
      if (commentText !== "") {
        var formData = $("#comment-form").serialize();
        // Get the comment submission URL from the data attribute
        var commentSubmitURL = "{% url 'article:comment_submit' post.slug %}";
        $.ajax({
          type: "POST",
          url: commentSubmitURL,
          data: formData,
          success: function(response) {
            // Clear the comment textarea after successful submission
            $("#comment-textarea").val("");
            // Render the new comment on the page
            renderComment(response);
          },
          error: function(error) {
            console.log(error);
          }
        });
      }
    });

    // Function to render a new comment on the page
    function renderComment(commentData) {
      var commentHtml = `
        <div class="comment">
          <div class="comment-header">
            <h3>${commentData.user}</h3>
            <span class="timestamp">${commentData.date_posted}</span>
          </div>
          <div class="comment-body">
            <p>${commentData.comment}</p>
          </div>
          <div class="comment-footer">
            <button class="comment-button"><i class="fa-solid fa-comment"></i>Reply</button>
            <button class="like-button"><i class="fas fa-heart"></i>Like</button>
            <button class="like-button"><i class="fa-solid fa-trash"></i>Delete</button>
          </div>
          <div class="child-comments">
            <!-- Child comments go here (if any) -->
          </div>
        </div>
      `;
      $("#comments-section").append(commentHtml);
    }
  });

for my python codes, the following are the relevant ones. In my models.py, I have:

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    image = models.ImageField()
    title = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, blank=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='posts', default='uncategorized')
    post = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    likes = models.ManyToManyField(User, blank=True, related_name="post_likes")
    is_edited = models.BooleanField(default=False)

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    comment = models.TextField()
    date_posted = models.DateTimeField(auto_now_add=True)

in my urls.py, I have:

path('comment_submit/<str:slug>/', views.comment_submit, name='comment_submit'),

in my views.py, I have:

def comment_submit(request, slug):
    if request.method == 'POST':
        # Get the comment data from the request and save it to the database
        comment_text = request.POST.get('comment')
        # Assuming you have already authenticated the user
        user = request.user
        post = Post.objects.get(slug=slug)
        comment = Comment.objects.create(post=post, user=user, comment=comment_text)
        comment_data = {
            'user': comment.user.username,
            'date_posted': comment.date_posted.strftime('%Y-%m-%d %H:%M:%S'),
            'comment': comment.comment,
        }
        return JsonResponse(comment_data)
    return JsonResponse({'error': 'Invalid request method'})

Please why does it not work as intended?

2

Answers


  1. #submit-comment is a button and you are preventing click event on that button.
    Instead you need to prevent the default form submit event.

    So, change $("#submit-comment").on("click", function(event)
    to:
    $("#comment-form").on("submit", function(event)

    Also, change type="button" to type="submit"

    Login or Signup to reply.
  2. It seems like there might be an issue with the Django blog’s comment functionality when using jQuery. Instead of processing the comment as expected, it redirects you to a JSON page, which is not the intended behavior.

    To troubleshoot this problem, there are a few things you can check:

    Verify jQuery Integration: Make sure you have included the jQuery library correctly in your Django project. Double-check the script tag in your HTML file to ensure that the jQuery library is loaded properly.

    Review AJAX Call: Check the AJAX call you are making for submitting the comment. Ensure that the URL and parameters are correct, and the method used is POST, as comments typically involve sending data to the server.

    Check Django View: Inspect the Django view that handles the comment submission. Ensure that it’s returning the appropriate JSON response or redirecting back to the blog post after processing the comment.

    Error Handling: Look for any error messages in the browser console or server logs that might give you clues about what’s going wrong.

    CSRF Token: If you are using Django’s built-in CSRF protection, ensure that the CSRF token is being included in your AJAX request headers. Without this token, Django views will reject the request.

    Cross-Origin Issues: Check for any cross-origin issues that might be preventing the AJAX call from functioning correctly.

    By reviewing these aspects, you should be able to identify the root cause of the problem and fix the comment functionality in your Django blog. Remember to test your changes thoroughly to ensure everything is working as expected.
    http://arnoldschwarzeneggers.com/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search