405 error on django ajax POST

Oscar Carballal picture Oscar Carballal · Oct 19, 2011 · Viewed 8.5k times · Source

I have a model with a integer field wich will increment on user click, like a "vote this" button.

The button only shows on the detail view. To increment the vote count it sends an ajax POST. The problem is that django returns a 405 (method not allowed) error even before executing the view. What can be causing this?

Here is my code:

views.py (doesn't get executed)

@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 code:

<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>

urls.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'),

)

Template

<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>

Answer

Jakub Roztocil picture Jakub Roztocil · Jan 3, 2012

Couldn't the problem be caused by the relative URL url: "../add_support_vote/" in $.ajax? I can imagine that another view that doesn't allow POST might be called instead of vote_proposal() depending on the location of the page from which you trigger the Ajax call.