为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

皈依舞 2022-12-27 17:20:39
您好,我正在尝试在 Django 中对我的博客应用程序的评论功能进行 ajax 化。现在代码工作正常,除了一个部分:我无法传输我想要访问我的views.py文件的对象 ID。当我对对象 ID 进行硬编码时,一切正常。views.py文件:(当我pk=request.POST.get('post_id')用实际的对象 ID 替换时,一切正常!)@login_requireddef 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()职能.
查看完整描述

1 回答

?
杨__羊羊

TA贡献1943条经验 获得超7个赞

问题是您的表单没有名称为的字段post_id。您已经添加name="post_id" value="{{ post.id }}"到您的提交按钮 - 但它不会被您的 html 表单视为表单字段。


正如我在评论中提到的,解决方案是添加一个隐藏的输入元素,如下所示:


<div>

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

        <div class="row">

        {{ comment_form.as_p }}

        {% csrf_token %}

        <input type="hidden" name="post_id" value="{{ post.id }}">

        <button type="submit" class="btn btn-info">Submit</button>

        </div>

    </form>

</div>

这样您的 html 表单就知道它必须提交字段post_id。希望能帮助到你


查看完整回答
反对 回复 2022-12-27
  • 1 回答
  • 0 关注
  • 141 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号