亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號