2017-05-05 170 views
-1

我將如何返回與Django的錯誤消息? 我想是這樣的(我使用jsonresponse一樣的我要怎麼做到這一點的例子):Django Ajax返回錯誤消息

def test(request): 
if request.method == "POST": 
    if form.is_valid(): 
     form.save 
     return JsonResponse({"message":"Successfully published"}) 
    else: 
     '''here i would like to return error something like:''' 
     return JsonResponse({"success": false, "error": "there was an error"}) 
else: 
    return JsonResponse({"success}: false, "error": "Request method is not post"}) 

我所試圖實現的是呈現在從阿賈克斯誤差函數模板的錯誤消息。類似這樣的:

$("#form").on("submit", function(){ 
     $.ajax({url: "url", 
       data: ("#form").serialize, 
       success: function(data){ 
       alert(data.message); 
       }, 
       error: function(data){ 
       alert(data.error); 
       } 
      }); 

會這樣嗎?

回答

1

試試這個。我認爲你的代碼中有一個語法錯誤。另外,如果你發佈錯誤信息會更好。我將false更改爲False

您還在代碼中省略了您的表單實例。

def test(request): 
    if request.method == "POST": 
     form = MyForm(request.POST) 
     if form.is_valid(): 
      form.save() 
      return JsonResponse({"message":"Successfully published"}) 
     else: 
      '''here i would like to return error something like:''' 
      return JsonResponse({"success": False, "error": "there was an error"}) 
    else: 
     return JsonResponse({"success}: False, "error": "Request method is not post"}) 
3

您當然可以從您的Django應用程序返回錯誤消息。但是你必須定義你想要返回的錯誤類型。爲此目的,你將不得不使用錯誤代碼。

最爲人所知的是404未找到頁面,500未能找到服務器錯誤。你也可以有403個禁止訪問......這取決於你想要治療的情況。您可以看到wikipedia page以查看可能性。

而是發送'success':False使用這個的:

response = JsonResponse({"error": "there was an error"}) 
response.status_code = 403 # To announce that the user isn't allowed to publish 
return response 

有了這個jQuery將認識到答案錯誤,你將能夠管理錯誤類型。

在JavaScript中管理你的錯誤:

$("#form").on("submit", function(){ 
    $.ajax({ 
     url: "url", 
     data: ("#form").serialize, 
     success: function(data){ 
      alert(data.message); 
     }, 
     error: function(data){ 
      alert(data.status); // the status code 
      alert(data.responseJSON.error); // the message 
     } 
    }); 
+0

等是可變STATUS_CODE已經在Django系統? – zzbil

+0

function(){return f &&(c &&!b &&(h = f.length-1,g.push(c)),function d(b){n.each(b,function(b,c){n.isFunction (三)a.unique && j.has(C)|| f.push(C):C && c.l ength && 「串」 == N.型(C)&& d(C)})}(! arg uments),c &&!b && i()),this}我在嘗試JavaScript代碼後得到這段代碼:data.error in ... – zzbil

+0

'status_code'是'JsonResponse'對象的對象變量。 Django直接將其解釋爲返回的錯誤/成功代碼。 –