当我习惯于评论时,它在div上显示得非常好但是没有从评论表中删除该值并且为了再次评论我必须刷新页面才能这样做。
请参阅视图功能和Main JS部分。
请帮助这方面,谢谢
views.py
def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug)
comments = Comment.objects.filter(post=post, parent=None)
if request.method == 'POST':
if not request.user.is_authenticated():
raise Http404
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
content = comment_form.cleaned_data['content']
parent_id = request.POST.get("parent_id")
print("Parent ID: ", parent_id)
parent_qs = None
if parent_id:
parent_qs = Comment.objects.filter(id=parent_id).first()
print("Parent QS: ", parent_qs)
new_comment, created = Comment.objects.get_or_create(
user=request.user,
post=post,
content=content,
parent=parent_qs
)
else:
comment_form = CommentForm()
context = {
"post": post,
"comments": comments,
"comment_form": comment_form,
}
if request.is_ajax():
return render(request, 'posts/partial_post_detail.html', context)
else:
return render(request, 'posts/post_detail.html', context)
post_detail.html
{% extends 'base.html' %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
{{ post.title }}<br>
Published by {{ post.user }}<br><br>
{{ post.content|linebreaks }}<br>
{% if post.user == request.user %}
<a href='{% url "posts:post_edit" slug=post.slug %}'>Edit</a>
<a href='{% url "posts:post_delete" slug=post.slug %}'>Delete</a>
{% endif %}
<hr>
<h1><b>Comments</b></h1>
<div id="div1">
{% include 'posts/partial_post_detail.html' %}
</div>
{% endblock %}
Partial_post_detail.html:
{% for comment in comments %}
<blockquote>
<p>{{ comment.content }}</p>
<footer>via {{ comment.user.username }} | {{ comment.timestamp|timesince }} ago | <a class="reply-btn">Reply</a></footer>
<div class="replied-comments" style="display:none;">
<blockquote> {% for child_comment in comment.replies.all %}
<p>{{ child_comment.content }}</p>
<footer>via {{ child_comment.user.username }} | {{ child_comment.timestamp|timesince }} ago</footer> {% endfor %} </blockquote>
<form method='POST' action='.' id="reply-form"> {% csrf_token %} {{ comment_form.as_p }} <input type='hidden' name='parent_id' value='{{ comment.id }}'></input> <input type='submit' value='Reply' class='btn btn-default'> </form>
</div>
</blockquote>
<hr> {% endfor %}
<form method='POST' action='.' id="comment-form"> {% csrf_token %}
{{comment_form.as_p }} <input type='submit' value='Post' class='btn btn-default'>
</form>
主要JS有AJAX:
$("#comment-form").submit(function(event) {
event.preventDefault();
var data= $(this).serialize();
alert(data)
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(data){
console.log(data);
$("#div1").html(data);
$(this).val('');
},
error: function(e){
console.log(e);
}
});
});
Models.py
class Comment(models.Model):
user = models.ForeignKey(User, default=1)
post = models.ForeignKey(Post)
parent = models.ForeignKey('self', null=True, blank=True, related_name='replies')
# content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
# object_id = models.PositiveIntegerField()
# content_object = GenericForeignKey('content_type', 'object_id')
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-timestamp']
def __str__(self):
return "{} - {}".format(str(self.user.username), str(self.post.title))
MAIN JS:
<script>
/* global $ */
$(document).ready(function(event) {
$("textarea").val("");
$('.reply-btn').click(function() {
console.log("Reply Button");
$(this).parent().next(".replied-comments").fadeToggle();
});
$("#comment-form").submit(function(event) {
event.preventDefault();
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(data){
console.log(data['form']);
data = data['form']
$("#div1").html(data);
$("textarea").val("");
$('.reply-btn').click(function() {
$(this).parent().next(".replied-comments").fadeToggle();
});
},
error: function(e){
console.log(e);
}
});
});
$("#reply-form").submit(function(event) {
event.preventDefault();
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(data){
data = data['form'];
console.log(data);
$("#div1").html(data);
$("textarea").val("");
$('.reply-btn').click(function() {
$(this).parent().next(".replied-comments").fadeToggle();
$('textarea').val('');
});
},
error: function(e){
alert(e);
}
});
});
// $("#id_username").prop("disabled", true);
// $("#id_email").prop("disabled", true);
});
</script>
答案 0 :(得分:0)
使用此
$("#comment-form").submit(function(event) {
event.stopPropagation();
var myform = $("#comment-form");
var data= $(this).serialize();
alert(data);
$.ajax({
data: $(myform).serialize(),
type: $(myform).attr('method'),
url: $(myform).attr('action'),
success: function(data){
console.log(data);
$("#div1").html(data);
$(myform +" textarea").val(' ');
$(myform +" input").val(' ');
},
error: function(e){
console.log(e);
}
});
});