簡體   English   中英

Django Ajax Comment正在更新和顯示,但內容並未從注釋表單中刪除

[英]Django Ajax Comment is updating and displaying but content is not removing from the comment form

當我以前使用Comment時,它可以很好地顯示在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>

具有AJAX的主要JS:

$("#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))

主要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>

用這個

$("#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);
                }
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM