gpt4 book ai didi

django - django ajax POST 上的 405 错误

转载 作者:行者123 更新时间:2023-12-01 11:04:05 25 4
gpt4 key购买 nike

我有一个带有整数字段的模型,它会在用户点击时增加,比如“投票这个”按钮。

该按钮仅显示在详细信息 View 中。为了增加投票计数,它发送一个 ajax POST。问题是 django 甚至在执行 View 之前返回 405(不允许的方法)错误。什么可能导致这种情况?

这是我的代码:

views.py(不会被执行)

@require_POST
def vote_proposal(request, space_name):

"""
Increment support votes for the proposal in 1.
"""
prop = get_object_or_404(Proposal, pk=request.POST['propid'])
proposal_form = VoteProposal(request.POST or None, instance=prop)

if request.method == "POST" and request.is_ajax:
if proposal_form.is_valid():
vote = proposal_form.cleaned_data['propid']
vote.support_votes += 1
vote.save()
msg = "The vote has been saved."
else:
msg = "The vote didn't pass validation."
else:
msg = "An error has ocurred."

return HttpResponse(msg)

jQuery代码:
<script type="text/javascript">
function upvote(proposal) {
var request = $.ajax({
type: "POST",
url: "../add_support_vote/",
data: { propid: proposal }
});

request.done(function(msg) {
var cur_votes = $("#votes span").html();
var votes = cur_votes += 1;
$("#votes span").html().fadeOut(1000, function(){
$("#votes span").html(votes).fadeIn();
});
});

request.fail(function(jqXHR, textStatus) {
$("#jsnotify").notify("create", {
title:"Couldn't vote the proposal",
text:"There has been an error." + textStatus,
icon:"alert.png"
});
})
}
</script>

网址.py
urlpatterns = patterns('e_cidadania.apps.proposals.views',

url(r'^$', ListProposals.as_view(), name='list-proposals'),

url(r'^add/$', 'add_proposal', name='add-proposal'),

url(r'^(?P<prop_id>\w+)/edit/$', 'edit_proposal', name='edit-proposal'),

url(r'^(?P<prop_id>\w+)/delete/$', DeleteProposal.as_view(), name='delete-proposal'),

url(r'^(?P<prop_id>\w+)/', ViewProposal.as_view(), name='view-proposal'),

url(r'^add_support_vote/', 'vote_proposal'),

)

模板
<div id="votes">
<span style="font-size:30px;text-align:center;">
{{ proposal.support_votes }}
</span><br/>
<button onclick="upvote({{ proposal.id }})" class="btn small">{% trans "support" %}</button>
</div>

最佳答案

问题不会是由相对 URL 引起的 url: "../add_support_vote/"$.ajax ?我可以想象可能会调用另一个不允许 POST 的 View 而不是 vote_proposal()取决于您触发 Ajax 调用的页面的位置。

关于django - django ajax POST 上的 405 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7819206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com