[英]Django Ajax views.py cannot get the Object ID and returns 404 instead
嗨,我正在尝试在 Django 中对我的博客应用程序的评论 function 进行 ajaxify。 现在代码工作正常,除了一部分:我无法传输我想访问我的views.py
文件的 Object ID。 当我对 Object ID 进行硬编码时,一切正常。
views.py
文件:(当我将pk=request.POST.get('post_id')
替换为实际的 obj 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()
function..
问题是您的表单没有名称为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
。 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.