如何将 django-comments 表单与 javascript 一起使用

How to use django-comments form with javascript?

本文关键字:javascript 一起 表单 django-comments      更新时间:2023-09-26

我有一个像系统一样的注释,请参见此处的图像:http://www.uploadscreenshot.com/image/1091218/5818195,单击注释时,您可以看到标题,消息和评论。我向他们发送 js 文件并在视图中设置它们。我的问题是我现在可以用 django 评论表单做到这一点吗?如果我只是粘贴到模板中并在引导弹出窗口中显示的div 中,并在注释 %} 中显示 {% 表示注释,它会显示该窗口上每个未包含的所有表单(可以理解)。

如何将正确的值传递给 django 注释表单?

这是js函数(只是相关的部分):

 request.done(function(note) {
    $('h3#view-note-title').text(note.title);
    $('p#view-note-desc').text(note.message);
    var html = '';
    for(var i=0; i<note.comments.length; i++) {
        var item = note.comments[i];
        html += "<p id='comments' style='display: block; background: #a3d95d;margin-bottom: 3px;'>" + item.comment + "</p>";
        html += "<p id='username' style='display: block;background: #edac65;margin-bottom: 3px;'>" + item.username + "</p>";
        html += "<p id='date' style='display: block;background: #afe9eb;margin-bottom: 13px;'>"+ item.submit_date +"</p>";
    }
    $('div#comments').html(html);
});

这是 views.py 的相关部分:

 if request.method == "GET" and request.is_ajax:
    note = get_object_or_404(Note, pk=request.GET['noteid'])
    ctype = ContentType.objects.get_for_model(Note)
    latest_comments = Comment.objects.filter(is_public=True, is_removed=False, content_type=ctype, object_pk=note.id).order_by('-submit_date')[:5]
    response_data = {}
    response_data['title'] = note.title
    response_data['message'] = note.message
    response_data['comments'] = [
        {'username': c.user.username, 'comment': c.comment, 'submit_date': c.submit_date} for c in latest_comments]
    return HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder), mimetype="application/json")

我希望我足够清楚。

解决方案是通过视图发送注释窗体。

代码:模板

<form id="form_comments" action="{% comment_form_target %}" method="post">
{% csrf_token %}
<table>
<tr>
  <td colspan="2">
    <div class="kopce"></div>
    <input type="submit" name="submit" value="Post">
    <input type="submit" name="preview" value="Preview">
  </td>
</tr>

观点:

from django.contrib.comments.forms import CommentForm
form = CommentForm(target_object = note)
response_data["form_html"] = form.as_p()

js:

 $('form#form_comments div.kopce').html(note.form_html);