title: How to submit django model forms via ajax, preventing reload/refresh on submit
body: <p>Problem: every time I click the login button, the page reloads and then goes to some funny URL appending 'undefined' in the URL - <a href="http://127.0.0.1:8000/accounts/userLogin/undefined" rel="nofollow noreferrer">http://127.0.0.1:8000/accounts/userLogin/undefined</a>. I would like if the form has errors, then the form errors are shown with the form again for the user to correct and if there are no errors, then log in the user.</p>
  
  <p>PS: I am relatively new to this Django/javascript world. </p>
  
  <p>Here is my code:</p>
  
  <ol>
  <li>View</li>
  </ol>
  
  <pre><code>@method_decorator(csrf_protect, name='post')
  class UserLogin(LoginView):
      """docstring for UserLogin"""
      template_name = 'accounts/login.html'
  
      def get(self, request):
          '''a func to work on the request.POST'''
          print("getting the form for you ")
          form = LoginForm()
          return render(request,self.template_name,{'form':form})
  
      def post(self, request):
          form = LoginForm(request.POST)
          print("go the data for you")
          if request.is_ajax():
              print("entered form")
              if form.is_valid():
                  print("form valid")
                  email = form.cleaned_data['email']
                  try:
                      user = User.objects.get(email=email)
                      print("user obj", user)
                      if user.check_password(form.cleaned_data['password']):
                          # 0-super admin, 1-dept admin,2-dept staff, 3-end user 
                          print("correct password")
                          if user.account_type == 4:
                              if user.last_login == None or user.last_login == '':
                                  to = "verify"
                              else:
                                  to = "user"
                          else:
                              if user.account_type == 2:
                                  to = 'dept_admin'
                              elif user.account_type == 3:
                                  to = 'dept_staff'
                              elif user.account_type == 1:
                                  to = 'super_user'
                              else:
                                  to = None
                          res = {'status':'ok', 'error':False, 'acc_type':to, 'data':user.email}
                      else:
                          print("incorrect password")
                          res = {'status':'fail', 'error':'incorrect password'}
                  except Exception as e:
                      print("User not found!", e)
                      res = {'status':'fail', 'error':'account not found'}
              else:
                  print("form valid")
                  res = {'status':'fail', 'error':form.errors}
          return JsonResponse(res)
  </code></pre>
  
  <ol start="2">
  <li>Form</li>
  </ol>
  
  <pre><code>{% load static %}
  
  &lt;!DOCTYPE html&gt;
  &lt;html lang="en"&gt;
    &lt;head&gt;
      &lt;meta charset="utf-8"&gt;
      &lt;title&gt;Login&lt;/title&gt;
      &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
      &lt;meta name="description" content=""&gt;
      &lt;meta name="author" content=""&gt;
      &lt;!-- Bootstrap core CSS --&gt;
      &lt;link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"&gt;
  
      &lt;!-- Font Awesome --&gt;
      &lt;link href="{% static 'css/font-awesome.min.css' %}" rel="stylesheet"&gt;
  
      &lt;!-- Endless --&gt;
      &lt;link href="{% static 'css/endless.min.css' %}" rel="stylesheet"&gt;
    &lt;/head&gt;
  
    &lt;body&gt;
      &lt;div class="login-wrapper"&gt;
          &lt;div class="text-center"&gt;
              &lt;span&gt;
                  &lt;img src="{% static 'img/question.png' %}" style="height: 100px; width: 100px; border-radius: 50%;"&gt;
              &lt;/span&gt;
          &lt;/div&gt;
          &lt;div class="text-center"&gt;
              &lt;h2 class="fadeInUp animation-delay8" style="font-weight:bold"&gt;
                  &lt;span class="text-success"&gt;CitiSpy User Login&lt;/span&gt;
              &lt;/h2&gt;
          &lt;/div&gt;
          &lt;div class="login-widget animation-delay1"&gt; 
              &lt;div class="panel panel-default"&gt;
                  &lt;div class="panel-heading clearfix"&gt;
                      &lt;div class="pull-left"&gt;
                          &lt;i class="fa fa-lock fa-lg"&gt;&lt;/i&gt; Login
                      &lt;/div&gt;
                  &lt;/div&gt;
                  &lt;div class="panel-body"&gt;
                      &lt;div id="login-form-main-message"&gt;&lt;/div&gt;
                      &lt;form class="form-login" id="login_form"&gt;
                          &lt;div id="form_content"&gt;
                              &lt;div class="form-group"&gt;
                              {% csrf_token %}
                              &lt;/div&gt; 
                              {{ form.non_field_errors }}
                              &lt;div class="form-group"&gt;
                                  {{ form.email.errors }}
                                  &lt;label&gt;Email&lt;/label&gt;
                                  {{ form.email }}
                              &lt;/div&gt;
                              &lt;div class="form-group"&gt;
                                  {{ form.password.errors }}
                                  &lt;label&gt;Password&lt;/label&gt;
                                  {{ form.password }}
                              &lt;/div&gt;        
                              &lt;div class="seperator"&gt;&lt;/div&gt;
                              &lt;hr/&gt;
                              &lt;div class="form-group"&gt;
                                  &lt;button class="btn btn-success btn-sm bounceIn animation-delay5 login-link pull-right" type="button"&gt;&lt;i class="fa fa-sign-in"&gt;&lt;/i&gt; Login&lt;/button&gt;
                                  &lt;!-- &lt;a type="submit" class="btn btn-success btn-sm bounceIn animation-delay5 login-link pull-right" id="login_submit"&gt;&lt;i class="fa fa-sign-in"&gt;&lt;/i&gt; Login&lt;/a&gt; --&gt;
                              &lt;/div&gt;     
                          &lt;/div&gt;
  
                      &lt;/form&gt;
                  &lt;/div&gt;
              &lt;/div&gt;&lt;!-- /panel --&gt;
          &lt;/div&gt;&lt;!-- /login-widget --&gt;
      &lt;/div&gt;&lt;!-- /login-wrapper --&gt;
      &lt;!-- Jquery --&gt;
      &lt;script src="{% static 'js/jquery-1.10.2.min.js' %}"&gt;&lt;/script&gt;
  
      &lt;!-- Bootstrap --&gt;
      &lt;script src="{% static 'bootstrap/js/bootstrap.js' %}"&gt;&lt;/script&gt;
  
      &lt;!-- Pace --&gt;
      &lt;script src="{% static 'js/uncompressed/pace.js' %}"&gt;&lt;/script&gt;
  
      &lt;!-- Popup Overlay --&gt;
      &lt;script src="{% static 'js/jquery.popupoverlay.min.js' %}"&gt;&lt;/script&gt;
  
      &lt;!-- Slimscroll --&gt;
      &lt;script src="{% static 'js/jquery.slimscroll.min.js' %}"&gt;&lt;/script&gt;
  
      &lt;!-- Modernizr --&gt;
      &lt;script src="{% static 'js/modernizr.min.js' %}"&gt;&lt;/script&gt;
  
      &lt;!-- Cookie --&gt;
      &lt;script src="{% static 'js/jquery.cookie.min.js' %}"&gt;&lt;/script&gt;
  
      &lt;!-- Endless --&gt;
      &lt;script src="{% static 'js/endless/endless.js' %}"&gt;&lt;/script&gt;
  
      &lt;!--login js--&gt;
      &lt;script src="{% static 'js/accounts/login_1.js' %}"&gt;&lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  
  </code></pre>
  
  <ol start="3">
  <li>JavaScript</li>
  </ol>
  
  <pre><code>$(function(){
      function getCookie(name) {
          var cookieValue = null;
          if (document.cookie &amp;&amp; document.cookie !== '') {
              var cookies = document.cookie.split(';');
              for (var i = 0; i &lt; 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;
      }
  
      var $csrf_token = {
          name: "csrfmiddlewaretoken",
          value: getCookie('csrftoken')
      };
  
      $('#login_form').submit(function(event){
          event.preventDefault();
          var $form_data = $(this).serializeArray();
          $form_data.push($csrf_token);
          $.ajax({
              type: 'POST',
              data: $form_data,
              cache: false,
              dataType: 'json',
              url: '/accounts/userLogin/',
              beforeSend: function(){
                  $("#login-form-main-message").css("display", "block").html("&lt;div class='alert alert-info'&gt;&lt;img height=\"24px;\" src=\"{% static '/images/double-ring.gif' %}\" alt=\"loading\" /&gt;  Please wait...&lt;/div&gt;");
                  $("#form_content").css("display", "none");
              },
              success: function(data){
                  if (data.status === "ok"){
                      if (data.to === "verify") {
                          //redirect to account verification
                      } else {
                          if (data.to === "user") {
                              //redirect to user account
                              $("#login-form-main-message").css("display", "block").html("&lt;div class='alert alert-info'&gt;&lt;img height=\"24px;\" src=\"{% static '/images/double-ring.gif' %}\" alt=\"loading\" /&gt; Success! login you in, please wait...&lt;/div&gt;");
                              $("#form_content").css("display", "none");
                          }else{
                              $("#login-form-main-message").css("display", "block").html("&lt;div class='alert alert-info'&gt;&lt;img height=\"24px;\" src=\"{% static '/images/double-ring.gif' %}\" alt=\"loading\" /&gt; Success! login you in, please wait...&lt;/div&gt;");
                              $("#form_content").css("display", "none");
                              location.href = '/em_dept/dashboard/';
                          }
                      }
                  }
              },
              error:function(){
                  console.log("error error error!!!");
              }
          });
          return false;
      });
  });
  </code></pre>