Display form errors with django and ajax

后端 未结 3 1019
盖世英雄少女心
盖世英雄少女心 2021-02-06 06:21

I have a contact form through which users would be able to contact me. I am using django with ajax, and it works fine if there\'s no error. I would like to show

3条回答
  •  南方客
    南方客 (楼主)
    2021-02-06 07:10

    as an example

    django form returns errors with json format using form.errors.as_json(). assume:

    {
        "sender": [
             {
               "message": "Enter a valid email address.", 
               "code": "invalid"
             }
        ],
    
        "subject": [
              {
                "message": "This field is required.", 
                "code": "required"
              }
        ]
    }
    

    after that, ajax get a response (in success: function(data) {}. assume already become an object:

        data = {
        "sender": [
        {
            "message": "Enter a valid email address.", 
          "code": "invalid"
        },
        {
            "message": "Enter a .", 
          "code": "invalid"
        }
      ], 
       "subject": [
        {
            "message": "This field is required.", 
          "code": "required"
        }
      ]
    };
    

    and you're already renders previous form, assume:

     

    and to render these messages, you can write scripts in the click events:

    // in ajax success (event click)
    if ($("input").next('p').length) $("input").nextAll('p').empty();
        for (var name in data) {
        for (var i in data[name]) {
          // object message error django
          var $input = $("input[name='"+ name +"']");
          $input.after("

    " + data[name][i].message + "

    "); } }

    simulation example:

    // simulation example, Data obtained from ajax response
    
    var data = {
    	"sender": [
      	{
        	"message": "Enter a valid email address.", 
          "code": "invalid"
        },
        {
        	"message": "Enter a .", 
          "code": "invalid"
        }
      ],
    	"subject": [
      	{
        	"message": "This field is required.", 
          "code": "required"
        }
      ]
    };
    
    $("button").on("click", function() {
    	if ($("input").next('p').length) $("input").nextAll('p').empty();
    	for (var name in data) {
        for (var i in data[name]) {
          // object message error django
          var $input = $("input[name='"+ name +"']");
          $input.after("

    " + data[name][i].message + "

    "); } } });
    
     

提交回复
热议问题