Django Ajax返回错误消息

zzb*_*bil 2 javascript python django ajax jquery

我如何使用django返回错误消息?我在想这样的事情(我正在使用jsonresponse作为我想要这样做的一个例子):

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"})
Run Code Online (Sandbox Code Playgroud)

我想要实现的是从ajax错误函数在模板中呈现错误消息.像这样的东西:

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

这可能吗?

Thi*_*and 11

您当然可以从Django App返回错误消息.但是您必须定义要返回的错误类型.为此,您必须使用错误代码.

最常见的是未找到页面的404或服务器错误的500.您还可以使用403进行禁止访问...这取决于您要处理的情况.您可以在维基百科页面上查看可能性.

而不是发送'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
Run Code Online (Sandbox Code Playgroud)

有了这个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
        }
    });
Run Code Online (Sandbox Code Playgroud)

  • 您还可以在 Django 中自定义消息: `response.reason_phrase = error`,然后在 JS 中您可以通过编写 `data.statusText` 来访问它 (2认同)

Tus*_*rtz 1

尝试这个。我认为您的代码中有语法错误。另外,如果您发布错误消息会更好。我将其更改falseFalse

您还是否在代码中省略了表单实例。

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"})
Run Code Online (Sandbox Code Playgroud)