3

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

该按钮仅显示在详细视图上。为了增加投票计数,它发送一个 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>
4

3 回答 3

6

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

于 2012-01-03T13:06:02.037 回答
1

Oscar 不幸的是,这项小型研究没有发现问题,但希望它能帮助您阐明如何修复代码以使其正常工作。

在 mainurls.py中,我为按钮创建了两个视图,第一个为按钮,第二个在 testap 中为 ajax 调用处理程序

from django.conf import settings
from django.conf.urls.defaults import patterns, include, url    
from django.views.generic.simple import direct_to_template

urlpatterns = patterns(''    
    url(r'^$', direct_to_template , {'template':'test.html'}),
    url(r'^test/', include('testapp.urls')),
)    

if settings.DEBUG:
    urlpatterns += patterns(
        '',
        url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)

出于测试目的,我的带有按钮的模板test.html有点简化。还添加了csrf 钩子以防止403 CSRF verification错误:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="{{ MEDIA_URL }}js/jquery-1.6.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ajaxSend(function(event, xhr, settings) {
        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        function sameOrigin(url) {
            // url could be relative or scheme relative or absolute
            var host = document.location.host; // host + port
            var protocol = document.location.protocol;
            var sr_origin = '//' + host;
            var origin = protocol + sr_origin;
            // Allow absolute or scheme relative URLs to same origin
            return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
                (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
                // or any other URL that isn't scheme relative or absolute i.e relative.
                !(/^(\/\/|http:|https:).*/.test(url));
        }
        function safeMethod(method) {
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }

        if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
        }
    });

       function upvote(proposal) {
           var request = $.ajax({
               type: "POST",
               url: "../test/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>
</head>
<body>
<div id="votes">
    <button onclick="upvote(1)" class="btn small">support</button>
</div>
</body>
</html>

urls.py从 testapp 看起来像

from django.conf.urls.defaults import *
from .views import vote_proposal

urlpatterns = patterns('',
    url(r'^add_support_vote/', vote_proposal),

)

并且views.py最大限度地简化了问题的本地化

from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_POST

@require_POST
def vote_proposal(request):
    return HttpResponse('ok')

它的作品。我有 200 个 HTTP 响应。


最后一个小建议用于resolve获取处理来自 ajax 调用的 url 的视图函数:

from django.core.urlresolvers import resolve
resolve('/test/add_support_vote/')
# returns ResolverMatch(func=<function vote_proposal at 0x2b17230>, args=(), kwargs={}, url_name='testapp.views.vote_proposal', app_name='None', namespace='')
于 2012-01-02T20:07:22.693 回答
0

我收到405 错误,因为我试图 POST 到一个TemplateView没有 POST 方法的地方,如果这对任何人都有帮助的话。

所以我把它改成了 a FormView(它有一个 POST 方法),它起作用了。

于 2015-03-24T13:32:27.773 回答