405 (METHOD NOT ALLOWED) for ajax request with dja

2019-06-16 11:15发布

I have the following Class Based View

class SupportView(BaseDetailView):

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

And following Jquery code:

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

And following url

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

But when I click the button i see 127.0.0.1:8000/profiles/support/ 405 (METHOD NOT ALLOWED) error. Any ideas ?

1条回答
贼婆χ
2楼-- · 2019-06-16 11:48

You have to implement the post method in your view:

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)

Since you didn't define the post method, it's the right behavior to get a 405 (METHOD NOT ALLOWED) error.

查看更多
登录 后发表回答