【发布时间】:2021-03-12 15:43:09
【问题描述】:
我遵循了一个关于如何在不重新加载页面和跳转到页面顶部的情况下提交 Django 评论表单的解决方案。我尝试了许多在线和离线的解决方案,但仍然没有解决方案。
表单工作正常,唯一的问题是提交时页面重新加载。
我是 Django 后端和 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>
【问题讨论】:
-
可以分享评论模型代码吗?这对您有任何帮助吗django-js-how-to-post-a-form-without-reloading-whole-page ?
-
如果您指定哪些有效,哪些无效,将会很有帮助
-
@AjayLingayat 我现在添加了模型代码。感谢您的链接,将检查它。
-
@ha-neul 一切正常,唯一的问题是当我提交评论时页面会重新加载,我想防止这种情况发生。
-
@MoAlaneth 看到我的回答。
标签: javascript html python-3.x django