title: CSRF token error when submitting different form after ajax login
body: <p>Page contains two forms, one for authentification and another for asking a question. The auth form is submitted via an AJAX call and successfully logs in the user. However, if the user submits the question form after login in, it throws "CSRF token missing or incorrect". </p>
  
  <p>main.js</p>
  
  <pre><code>$(function() {
      // Submit post on submit
      $('#login-form').on('submit', function(event){
          event.preventDefault();
          console.log("form submitted!")
          create_post();
      });
  
      // AJAX for auth
      function create_post() {
          $.ajax({
              url : "perfil/entrar/", // the endpoint
              type : "POST", // http method
              data : { username : $('#username-text').val(), password : $('#password-text').val() }, // data sent with the post request
              // handle a successful response
              success : function(json) {
                  $('#username-text').val(''); // remove the value from the input
                  $('#password-text').val(''); // remove the value from the input
              },
              // handle a non-successful response
              error : function(xhr,errmsg,err) {
                  console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
              }
          });
      };
  
  
      // This function gets cookie with a given name
      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 csrftoken = getCookie('csrftoken');
  
      /*
      The functions below will create a header with csrftoken
      */
  
      function csrfSafeMethod(method) {
          // these HTTP methods do not require CSRF protection
          return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
      }
      function sameOrigin(url) {
          // test that a given url is a same-origin URL
          // url could be relative or scheme relative or absolute
          var host = document.location.host; // host + port
          var protocol = document.location.protocol;
          var sr_origin = '//' + host;
          var origin = protocol + sr_origin;
          // Allow absolute or scheme relative URLs to same origin
          return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
              (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
              // or any other URL that isn't scheme relative or absolute i.e relative.
              !(/^(\/\/|http:|https:).*/.test(url));
      }
  
      $.ajaxSetup({
          beforeSend: function(xhr, settings) {
              if (!csrfSafeMethod(settings.type) &amp;&amp; sameOrigin(settings.url)) {
                  // Send the token to same-origin, relative URLs only.
                  // Send the token only if the method warrants CSRF protection
                  // Using the CSRFToken value acquired earlier
                  xhr.setRequestHeader("X-CSRFToken", csrftoken);
              }
          }
      });
      // Open modal dialog for authentification
      $('#myModal').on('shown.bs.modal', function () {
        $('#myInput').focus()
      });
  
  });
  </code></pre>
  
  <p>index.html</p>
  
  <pre><code>            &lt;form method="post" id=class="form-horizontal" action="/perguntar/"&gt;
                  {% csrf_token %}
                          &lt;div class="col-md-7"&gt;
                          {{ questionform.title }}
                          {{ questionform.title.errors }}
                          {{ questionform.body }}
                          {{ questionform.body.errors }}
                          &lt;/div&gt;
                          &lt;div class="form-group"&gt;
                              &lt;div class="col-sm-4"&gt;
                                  &lt;div class="input-group"&gt;
                                      &lt;div class="input-group-addon"&gt;$&lt;/div&gt;
                                      &lt;div&gt;{{ questionform.orcamento }}&lt;/div&gt;
                                      {{ questionform.orcamento.errors }}
                                      &lt;div class="input-group-addon"&gt;,00&lt;/div&gt;
                                  &lt;/div&gt;
                                  {{ questionform.category }}
                                  {{ questionform.category.errors }}
                                  &lt;button type="submit" class="btn btn-primary btn-block"&gt;Perguntar&lt;/button&gt;
                              &lt;/div&gt;
                          &lt;/div&gt;
              &lt;/form&gt;
  
                          &lt;form method="POST" id="login-form"&gt;
                            {% csrf_token %}
                          &lt;label for="username-text"&gt;Usuario:&lt;/label&gt;
                          &lt;input type="text" name="username" value="" id="username-text"&gt;
                          &lt;label for="password-text"&gt;Senha:&lt;/label&gt;
                          &lt;input type="password" name="password" value="" id="password-text"&gt;
                          &lt;input type="submit" value="login" /&gt;
                          &lt;input type="hidden" name="next" value="{{ next|escape }}" /&gt;
                         &lt;/form&gt;
  </code></pre>
  
  <p>login_view</p>
  
  <pre><code>def login_view(request):
      if request.method == 'POST':
          response_data = {}
          username = request.POST.get('username', '')
          password = request.POST.get('password', '')
          user = auth.authenticate(username=username, password=password)
          if user is not None and user.is_active:
              auth.login(request, user)
              response_data['result'] = 'success'
              return HttpResponse(
                          json.dumps(response_data),
                          content_type="application/json"
              )
          else:
              return render(request, 'error.html', {
          })
      else:
          return render(request, 'login.html', {
          })
  </code></pre>
  
  <p>askQuestion_view</p>
  
  <pre><code>def perguntar(request):
      if request.method == 'POST':
          form = ModelThreadForm(request.POST)
          if form.is_valid():
              thread = form.save(commit=False)
              if request.user.is_authenticated():
                  thread.published = True
                  thread.creator = request.user
                  thread.save()
              else:
                  thread.published = False
                  thread.creator = None
                  thread.save()
          return HttpResponseRedirect(thread.get_absolute_url())
      else:
          form = ModelThreadForm()
      return render(request, 'perguntar.html', {
                                 'questionform': form,
      })
  </code></pre>
  
  <p>I've tried using </p>
  
  <pre><code>    data : { 'csrftoken': '{{ csrf_token }}', username : $('#username-text').val(), password : $('#password-text').val() }, // data sent with the post request
  </code></pre>
  
  <p>Instead of</p>
  
  <pre><code>        data : { 'X-CSRFToken': '{{ csrf_token }}', username : $('#username-text').val(), password : $('#password-text').val() }, // data sent with the post request
  </code></pre>
  
  <p>And eliminating the sameOrigin function on main.js. Neither had any effect on the behaviour. </p>