H
H
howuu2019-02-05 16:55:51
JavaScript
howuu, 2019-02-05 16:55:51

How to make jquery ajax request callback in django login form?

I'm making a custom django admin panel, in the authorization form everything is like this

<form method="post" class="form-signin">
       {% csrf_token %}

      <img class="mb-4" src="{% static 'images/icons/logo.png' %}" alt="" width="72" height="72">
      <h1 class="h3 mb-3 font-weight-normal">Залогінься сучка</h1>

      <label for="inputEmail" class="sr-only">Email address або username</label>
      <input type="#" id="inputEmail" class="form-control username" placeholder="Email address або username" required="" autofocus="">
      <label for="inputPassword" class="sr-only">Пароль</label>
      <input type="password" id="inputPassword" class="form-control password" placeholder="Пароль" required="">
      <div class="checkbox mb-3">
        
      </div>
      

       <button type="button" class="btn btn-lg btn-primary btn-block" onclick="zapros()">Увійти</button>
      <p class="mt-5 mb-3 text-muted">@howareu_u</p>
    </form>


in js like this

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}


function zapros() {

  var username  = $( ".username").val();
  var parol = $( ".password").val();


  
  var csrftoken = getCookie('csrftoken');
  data = {'csrfmiddlewaretoken':  csrftoken, username: username, password: parol };

  $.ajax({
          url: '/accounts/login/',
          type: "POST",
          data: data 
        })  ;
  }


Everything works in cookies, our authorization appears, but we are not thrown to another page (this is how it should be when we display the authorization form in the standard django way
<form method = post>
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Login</button>
</form>

and authorize in this way, then we are thrown, but when we make the same post request through jQuery, then no.
Also, the form does not tell us if there were errors entered when trying to authorize, in general, the question is how to make the admin panel custom, so that we have the styles we need, and we were told about errors and it was LOGIN_REDIRECT_URL = 'our link' using django.auth

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question