405(方法不允许)使用django进行ajax请求

时间:2013-06-18 22:12:51

标签: jquery ajax django http

我有以下基于类的视图

class SupportView(BaseDetailView):

    def render_to_response(self):
       if self.request.method == "POST":
            message = "YES"
       else:
            message = "NO"
       return HttpResponse(message)

遵循Jquery代码:

    <script>
var username = $('.username').attr('data-username');
$('.destek').click(function(){
    $.ajax({
        url:"/profiles/support/",
        type:"POST",
        data:{"username":username, 'csrfmiddlewaretoken': '{{csrf_token}}'},
        dataType:"json"
    })
})
</script>

关注网址

   url(r'^support/$', SupportView.as_view())

但是当我点击按钮时,我会看到127.0.0.1:8000/profiles/support/ 405 (METHOD NOT ALLOWED) error. Any ideas ?

1 个答案:

答案 0 :(得分:18)

您必须在视图中实施post方法:

class SupportView(BaseDetailView):
    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        return self.render_to_response(context)

由于您没有定义post方法,因此获得405 (METHOD NOT ALLOWED) error是正确的行为。