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



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

views.py文件:(当我用实际的 obj ID 替换pk=request.POST.get('post_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()职能。

问题是您的表单没有名称为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.希望对你有帮助

最新更新