Display form errors using django and ajax

I have a contact form through which users can contact me. I use django with ajax and it works fine if there is no error. I would like to show errors if they are visible above the input fields, not just errors, but both input and errors. However, it distinguishes the result successand errorsince the ajax request was successful. But I need to display the actual form errors. How am I doing this? Your help will be greatly appreciated. Thanks.

Views:

def contact(request):
    if request.is_ajax() and request.POST:
        form = ContactForm(request.POST)
        if form.is_valid():
            new_contact = form.save()
            data = {
                'result': 'success',
                'message': 'Message Sent.'
            }
            return JsonResponse(data)
        else:
            data = {
                'result': 'error',
                'message': 'Form invalid',
                'form': 'oops.'
            }
            return JsonResponse(data)
    else:
        form = ContactForm()
        return render(request, 'public_contact.html', {
            'form': form
        })

JS:

contact_right_form.find('#submit').on('click', function(event) {
    event.preventDefault();
    $.ajax({
        type: contact_right_form.attr('method'),
        url: '/contact/',
        data: contact_right_form.serialize(),
        dataType: 'json',
        success: function(data) {
            if ( data.result == 'success') {
                contact_right_message_sent.text(data.message);
                contact_right_message_sent.show();
            }
            else {
                contact_right_message_sent.text(data.message);
                contact_right_message_sent.show();
            }
        },
        error: function() {
            contact_right_message_sent.text('Sorry! Something went wrong.')
        }
    });
})

Update

I would like to display errors as shown below, as is usually done without ajax:

enter image description here

+4
source share
3

json , html . .

, , , .

, /form.html,

{% include 'form.html' %}

form_invalid html

return render(self.request, 'form.html', {'form' : form}, status=500)

JS error html, .

+4

status_code JsonResponse.

return JsonResponse(data, status_code=400)

, error $.ajax.

+3

django json, form.errors.as_json(). :

{
    "sender": [
         {
           "message": "Enter a valid email address.", 
           "code": "invalid"
         }
    ],

    "subject": [
          {
            "message": "This field is required.", 
            "code": "required"
          }
    ]
}

ajax ( success: function(data) {}. , :

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

, :

<input type="text" name="sender"> <br>
<input type="text" name="subject"> <br>
<button>Submit</button>

and to display these messages you can write scripts in 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("<p>" + data[name][i].message + "</p>");
    }
  }

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("<p>" + data[name][i].message + "</p>");
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="sender"> <br>
<input type="text" name="subject"> <br>
<button>Submit</button>
Run code
+1
source

Source: https://habr.com/ru/post/1621654/


All Articles