Django, Ajax i JS. Jak zapobiec ponownemu ładowaniu strony i przeskakiwaniu na górę strony, gdy przesyłam komentarz

Dec 01 2020

Podążyłem za rozwiązaniem, w jaki sposób uzyskać formularz komentarza Django, aby przesłać go bez przeładowywania strony i przeskakiwania na górę strony. Próbowałem wielu rozwiązań online i offline, ale nadal nie mam rozwiązania.

Formularz działa poprawnie, jedynym problemem jest ponowne załadowanie strony po przesłaniu.

Jestem nowy w Django Backend i Ajax, będę szczęśliwy, jeśli ktoś może pomóc, jak sobie z tym poradzić. Z góry dziękuję.

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>

Odpowiedzi

Hisham___Pak Dec 01 2020 at 01:15

Możesz zapobiec przeładowaniu strony, dodając 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;
    });