Django Ajax views.py 无法获取对象 ID 而是返回 404

您好,我正在尝试在 Django 中对我的博客应用程序的评论功能进行 ajax 化。现在代码工作正常,除了一个部分:我无法传输我想要访问我的views.py文件的对象 ID。当我对对象 ID 进行硬编码时,一切正常。


views.py文件:(当我pk=request.POST.get('post_id')用实际的对象 ID 替换时,一切正常!)


@login_required

def comment_create(request):

    post = get_object_or_404(Post, pk=request.POST.get('post_id'))

    user = get_object_or_404(User, username=request.user)

    comment_form = CommentForm()


    if request.method == 'POST':

        comment_form = CommentForm(data=request.POST)

        if comment_form.is_valid():

            new_comment = comment_form.save(commit=False)

            new_comment.post = post

            new_comment.author = user

            new_comment.save()

    else:

        comment_form = CommentForm()


    if request.is_ajax():

        html = render_to_string('feed/comment_section.html', {'post': post}, request=request)

        return JsonResponse({'form': html})

我的 html 中的评论表单:


<div>

    <form class="comment-form" action="{% url 'comment-create' %}" method="POST">

        <div class="row">

        {{ comment_form.as_p }}

        {% csrf_token %}

        <button type="submit" name="post_id" value="{{ post.id }}" class="btn btn-info">Submit</button>

        </div>

    </form>

</div>

我的 jQuery 事件处理程序:


$(document).on('submit', '.comment-form', function(event){

                event.preventDefault();

                console.log($(this).serialize());

                $.ajax({

                    type: 'POST',

                    url: $(this).attr('action'),

                    data: $(this).serialize(),

                    dataType: 'json',

                    success: function(response) {

                        $('#comment-section').html(response['form']);

                        console.log($('#comment-section').html(response['form']));

                    },

                    error: function(rs, e){

                        console.log($(rs.responseText));

                    },

                });

            });

我尝试了各种方法,但我不知道如何确保将其post_id移交给我的comment_create()职能.


皈依舞
浏览 158回答 1
1回答

杨__羊羊

问题是您的表单没有名称为的字段post_id。您已经添加name="post_id" value="{{ post.id }}"到您的提交按钮 - 但它不会被您的 html 表单视为表单字段。正如我在评论中提到的,解决方案是添加一个隐藏的输入元素,如下所示:<div>&nbsp; &nbsp; <form class="comment-form" action="{% url 'comment-create' %}" method="POST">&nbsp; &nbsp; &nbsp; &nbsp; <div class="row">&nbsp; &nbsp; &nbsp; &nbsp; {{ comment_form.as_p }}&nbsp; &nbsp; &nbsp; &nbsp; {% csrf_token %}&nbsp; &nbsp; &nbsp; &nbsp; <input type="hidden" name="post_id" value="{{ post.id }}">&nbsp; &nbsp; &nbsp; &nbsp; <button type="submit" class="btn btn-info">Submit</button>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </form></div>这样您的 html 表单就知道它必须提交字段post_id。希望能帮助到你
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python