保存Django AJAX评论

时间:2016-05-26 21:27:32

标签: json ajax django django-forms django-views

我在我的Django项目中添加了AJAX注释,但注释未保存。你能告诉我哪里有错吗?

这是AJAX文件:

$(document).ready(function () {
$('#comment-form').on('submit', function (event) {
    event.preventDefault();
    console.log("form submitted!")  // sanity check
    create_comment();
});
function create_comment() {
    console.log("create comment is working!")
    $.ajax({
        url: "/friends_plans/new_comment/",
        type: "POST",
        headers: {"X-CSRFToken": getCookie("csrftoken")},
        data: {text: $('#comment-text').val(), wish_list_id: $('#wish_list_id').val()},
        success: function (json) {
            $('#comment-text').val('');
            console.log(json);
            $("#comments").append('<div class="row"><div class="panel panel-default"><div class="panel-body">'+json.text+'</p><p style="float: right">'+json.person+', &nbsp</p></div></div><br>');
        },
        error: function () {
            alert("some erors!");
        }
    });
};
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}
});

这是来自views.py:

的功能
def new_comment(request):
form = Comment_to_wish_listForm(request.POST)
print ("function1")
if form.is_valid():
    print ("function2")
    data = request.POST.copy()
    wish_list_id = data['wish_list_id']
    text = data['text']
    wish_list = Wish_list.objects.get(id=wish_list_id)
    comment = Comment_to_wish_list(text=text, comment_to=wish_list, person=request.user)
    comment.save()
    response_data = {}
    response_data['text'] = comment.text
    response_data['person'] = comment.person.username
    return HttpResponse(
        json.dumps(response_data),
        content_type="application/json"
    )
return render(request, 'friends_plans/index.html', {})

这是模板的一部分:

            ...
            <h3> Comments </h3>
            {% if message %}
                <p style="color:red">{{ message }}</p>
            {% endif %}
            <div id="comments">
                {% for comment_to_wish_list in wish_list.comment_to_wish_list_set.all %}
                    <div class="row">
                        <div class="col-sm-12">
                            <div class="panel panel-default">
                                <div class="panel-body">
                                    {{ comment_to_wish_list.text }}
                                </div>
                            </div>
                            <p style="float: right"> {{ comment_to_wish_list.person }}</p>
                        </div>
                    </div>
                    <br>
                {% endfor %}
            </div>
            {% if user.is_authenticated %}
                <form id="comment-form" action="/new_comment/{{wish_list.id }}/" method="post">
                    {% csrf_token %}
                    <div class="form-group">
                        {{ form.text }}
                        <input type="text" name="text" id="comment-text" placeholder="Text" width="250" height="50" value="">
                    </div>
                    <input type="hidden" name="wish_list_id" id="wish_list_id" value="{{ wish_list.id }}">
                    <div class="form-group">
                        <input type="submit" name="create-comment" id="create-comment" value="Create">
                    </div>
                </form>
            {% else %}
                <p>Log in or register! </p>
            {% endif %}
            ...

这是网址:

url(r'^new_comment/$', views.new_comment, name="new_comment")

使用POST方法一切正常。我可以看到来自print ("function1")的消息,但没有来自print ("function2")的消息,并且评论未保存。另一个问题是AJAX文件中的函数被调用了两次,我无法理解为什么。

0 个答案:

没有答案