我想为我的页面创建一个评论系统。该系统无需刷新页面即可正常工作。我是Ajax的新手,可能遗漏了一些东西,但我不知道是什么。当我单击“评论”按钮时,页面显示类似的内容;
我的代码:
view.py
def post_detail(request, pk, ):
post = get_object_or_404(Post, pk=pk)
form = CommentForm(request.POST or None)
if form.is_valid():
name = request.POST['name']
content = request.POST['content']
comment = Comment()
comment.name = name
comment.content= content
return JsonResponse(model_to_dict(comment), safe=False)
context = {
'post': post,
'form': form,
}
return render(request, 'blog/post_detail.html', context)
models.py
class Comment(models.Model):
name = models.CharField(max_length=200, verbose_name='name')
content = models.TextField(verbose_name='comment')
created_date = models.DateTimeField(auto_now_add=True)
comment.html
{% load crispy_forms_tags %}
<hr>
<form method="POST" style="width: 50%; margin-left: 20px" id="comment_form">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" class="btn btn-info" value="Yorum Ekle" style="margin-left: 20px">
</form>
post_detail.html
...
<div id="comment">
<h2>Yorum Ekle:</h2>
{% include 'blog/comment.html' %}
<hr>
{% for comment in post.comments.all %}
<h4>{{ comment.name }} |
<small>{{ comment.created_date|timesince }} önce</small>
</h4>
<p>{{ comment.content|linebreaks }}</p>
{% endfor %}
</div>
<hr>
<hr>
<script type="text/javascript" src="{% static 'js/jquery-1.11.1.min.js' %}"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#comment|form").submit(function (e) {
e.preventDefault();
var url = "/post/12";
$.ajax({
type: 'POST',
url: url,
data: $("#comment_form").serializeArray(),
success: function (data) {
console.log('SUCCESS');
}
});
});
});
</script>
forms.py `
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = [
'name',
'content',
]
我的错误是什么,我该如何解决?请帮我。感谢您的关注。
答案 0 :(得分:0)
选择器语法有问题:
$(document).ready(function () {
$("#comment|form").submit(function (e) {
...
在您的post_detail.html文件中, $("#comment|form")
应该是$("#comment_form")
。