django通过ajax渲染模板变量和标签

时间:2018-04-19 03:57:49

标签: python ajax django variables django-templates

我想使用Django + jquery-ajax来刷新我的博客的新评论。

代码如下:

views.py:

@require_POST
def wirte_comment(request):
    """ajax new article comment"""
    if request.user.is_anonymous:
        login_url = reverse('login')
        return JsonResponse({'status': 'redirect',
                             'login_url': login_url})
    # logined
    article_id = int(request.POST.get('article_id'))
    comment_form = ArticleCommentForm(request.POST)
    article = get_object_or_404(Article, id=article_id)
    if comment_form.is_valid():
        new_comment = comment_form.save(commit=False)
        new_comment.author = request.user
        new_comment.article = article
        new_comment.save()
        create_action(request.user, article,
                      verb=f"{request.user.username} commentted《{article.title}》")
        # comment html
        with open('blog/templates/blog/add_comment.html') as f:
            html = f.read()
        return JsonResponse({'status': 'ok',
                             'html': html})
    else:
        return JsonResponse({'status': 'ko'})

我将新评论的HTML作为字符串发送到前端:

add_comment.html:

<div class="comment">
        <p class="comment-author">
            <a href="{% url 'account:user_detail' article.author %}">
                {% avatar article.author 25 class="circle-avatar" %}
            </a>
            <a href="{% url 'account:user_detail' article.author %}">
                {{ article.author }}
            </a>
            {{ comment.created |date:'y/m/d h:i' }}
        </p>
        <p>{{ comment }}</p>
    </div>

article.html

<script>
    $(document).ready(function () {
        $('#new_comment').click(function () {
            var text = $('#text').val();
            $.post(comment_url,
                {
                    article_id: article_id,
                    content: text
                },
                function (data) {
                    if (data['status'] === 'redirect') {
                        window.location.href = data['login_url'];
                    }
                    if (data['status'] === 'ok') {
                        $('#comment-list').prepend(data['html']);
                    }
                }
            );
        });
    });
</script>

然后出现问题: 当我提交新评论时,它会呈现如下:

{% avatar article.author 25 class="circle-avatar" %} {{ article.author }} {{ comment.created |date:'y/m/d h:i' }}

{{ comment }}

我该如何解决这个问题?

非常感谢。

1 个答案:

答案 0 :(得分:0)

我认为你需要将你的逻辑包装在ajax调用的成功函数中。

 $(document).ready(function () {
    $('#new_comment').click(function () {
        var text = $('#text').val();
        $.ajax({
            url:comment_url,    
            data : {
                    article_id: article_id,
                    content: text
                },
            dataType: 'json',
            success: function (data){
                if (data['status'] === 'redirect') {
                    window.location.href = data['login_url'];
                }
                if (data['status'] === 'ok') {
                    $('#comment-list').prepend(data['html']);
                }
            }
        })
    })
});