我有一个带有整数字段的模型,它将在用户单击时增加,例如“投票”按钮。
该按钮仅显示在详细视图上。为了增加投票计数,它发送一个 ajax POST。问题是 django 甚至在执行视图之前返回 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>