Django, Ajax 및 JS. 댓글을 제출할 때 페이지 새로 고침을 방지하고 페이지 상단으로 점프하는 방법

Dec 01 2020

페이지를 다시로드하고 페이지 맨 위로 점프하지 않고 제출할 Django 주석 양식을 얻는 방법에 대한 솔루션을 따랐습니다. 온라인과 오프라인에서 많은 솔루션을 시도했지만 여전히 솔루션이 없습니다.

양식이 올바르게 작동하지만 유일한 문제는 제출시 페이지를 다시로드하는 것입니다.

저는 Django Backend와 Ajax를 처음 사용합니다. 누군가이 문제를 처리하는 방법에 대해 도움을 줄 수 있다면 기쁩니다. 미리 감사드립니다.

JS AJAX

$( document ).ready(function() { $(`.comment-form${post_id}`).submit(function() { $.ajax({
              data: $(this).serialize(), type: $(this).attr('method'), 
              url: $(this).attr('action'), success: function(response) { $();
              },
              error: function(response) {
                console.log('error', response)
             }
          });
          return false;
    });
});

models.py

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
from django.db import models

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    body = models.TextField(max_length=300)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.pk)
VIEWS

from django.shortcuts import render, redirect
from .models import Post, Like
from django.contrib.auth.models import User
from .forms import CommentModelForm
from django.http import JsonResponse

# Create your views here.

def post_comment_create_and_list_view(request):
    qs = Post.objects.all()
    user = User.objects.get(pk=request.user.pk)


    #Comment form
    c_form = CommentModelForm()
        
    if 'submit_c_form' in request.POST:
        c_form = CommentModelForm(request.POST)
        if c_form.is_valid():
            instance = c_form.save(commit=False)
            instance.user = user
            instance.post = Post.objects.get(id=request.POST.get('post_id'))
            instance.save()
            c_form = CommentModelForm()

    
    context = {
    'qs': qs,
    'user':user,
    'c_form':c_form,
    }

    return render(request, 'posts/main.html', context)
HTML

<form action="" method="POST" class="comment-form" id='{{obj.id}}'>
{% csrf_token %}
  <div class="input-group">
    <input type="hidden" name="post_id" value={{obj.id}}> 
    
    {{ c_form }}
    <div class="input-group-append">
      <button type="submit" name="submit_c_form" class="btn btn-md u-btn-white g-color-red g-text-underline-hover g-brd-gray-light-v3 g-brd-none g-brd-top">Post</button>
      </div> 
    </div>
</form>

답변

Hisham___Pak Dec 01 2020 at 01:15

추가하여 페이지 새로 고침을 방지합니다. e.preventDefault();

$(`.comment-form${post_id}`).submit(function(e) { // Note here too, on submit a function in created where we catch e
      e.preventDefault(); // Here it is e is an event which is passed on clicking button
      $.ajax({ data: $(this).serialize(), 
          type: $(this).attr('method'), url: $(this).attr('action'), 
          success: function(response) {
              $();
          },
          error: function(response) {
            console.log('error', response)
         }
      });
      return false;
    });