您好,我正在嘗試在 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。希望能幫助到你
添加回答
舉報
0/150
提交
取消