M
M
mashincode2021-05-14 15:54:25
AJAX
mashincode, 2021-05-14 15:54:25

How to accept passwords in Django Ajax form display error?

I'm using Django forms and Jquery, I have a sign-up form that asks for email, passwords, first name, last name, phone number.

It is written in js that every time any of the inputs changes, I submit the form to django for subsequent validation

function send_ajax(){
  var form_id = $("#ajax_signup_form");

  $.ajax({
    url: "{% url 'signup' %}",
    type: "POST",
    data: form_id.serialize(),
    async: true,
    header: {'X-CSRFToken': '{{ csrf_token }}'},
    success: function(data) {
       var success = data['success'];
       if (success) {
        console.log('Success in response ')
       } else {
          form_id.replaceWith(data['html']);
       }
    },
    error: function (data) {
      console.log('Error in response')
    }
  });
}

$(document).on('change', $(".ajax_signup_element") ,function(){
  send_ajax();
})


This is how I take it:

...

if request.method == 'POST' and request.is_ajax():
  form = SignUpForm(request.POST)
  resp = {}

  if form.is_valid():
      form.save()
  else:
      resp['success'] = False
      csrf_context = {}
      csrf_context.update(csrf(request))
      form_html = render_crispy_form(form, context=csrf_context)
      resp['html'] = form_html
  return HttpResponse(json.dumps(resp), content_type='application/json')
...


It turns out that the form goes back and displays errors, leaving the values ​​​​in the previous fields the same entered, however, the passwords are removed every time, how to make sure that the passwords are also filled in?

609e72db946dd887004222.png

609e72e4b5f92074615596.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kuznetsov, 2021-05-14
@mashincode

As an option - save to another variable and / or return a duplicated variable and then substitute it in the desired field.
Either the framework itself, or the browser (I don’t remember exactly, like the first one) specifically protects against such manipulations. So go ahead and test.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question