2016-10-11 43 views
2

我想要做的是不允許一般POST請求,只接受ajax請求。Django:如何讓視圖只接受ajax請求?

class CustomerInfoCheckView(View): 

    def post(self, request, *args, **kwargs): 
     # CustomerInfoForm by ajax request 
     if request.is_ajax(): 
      form = CustomerInfoForm(
       request.POST, 
      ) 

      if form.is_valid(): 
       return JsonResponse(
        data={ 
         "valid": True, 
        } 
       ) 
      else: 
       return JsonResponse(
        data={ 
         "valid": False, 
         "errors": form.errors 
        } 
       ) 
     else: 
      return Http404 

但問題是,是顯示錯誤: AttributeError: type object 'Http404' has no attribute 'get'

我該如何處理?

回答

3

Http404是一個例外,而不是HttpResponse對象,所以你應該提高它的代替回報

raise Http404 

或者,您也可以返回django.http.HttpResponseNotFound具有大致爲提高上述例外同樣的效果:

return HttpResponseNotFound("Page not found") 

順便說一下,我會創建一個custom decorator,檢查是否請求我而不是用if/else子句污染視圖代碼。

您可以使用method_decorator功能,使基於階級享有定製的裝飾工作:

from django.utils.decorators import method_decorator 

class CustomerInfoCheckView(View): 
    @method_decorator(ajax_required) 
    def post(self, request, *args, **kwargs): 
     ... 
+0

可這也適用於基於功能的看法? – BRHSM