title: CSRF token missing on file upload ajax request
body: <p>I have an ajax request that sends a file to django, it is saying that the csrf token is missing but i copied my other ajax request that are working. I'm sure it has something to do with trying to pass a file to upload.</p>
  
  <p>I get a 403 and csrf missing return.</p>
  
  <p>base.html</p>
  
  <pre><code>&lt;script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'&gt;&lt;/script&gt;
  &lt;script type="text/javascript"&gt;
      $(document).ready(function() {  
                  $("#create_token").click(function() {
                          var username = document.getElementById("username").value;
                          $.ajax({
                              url : "/gettoken/", 
                              type : "POST",
                              dataType: "json", 
                              data : {
                                  csrfmiddlewaretoken: '{{ csrf_token }}',
                                  create_token: 'create_token',
                                  username: username,
                                  },
                                  success : function(json) {
                                      document.getElementById('output').innerHTML = ('Token: ' + json['token']);
                                  },
                                  error : function(xhr,errmsg,err) {
                                      console.log(xhr.status + ": " + xhr.responseText);
                                      document.getElementById('output').innerHTML = "Token:" + " Request Failed.";
                                  }
  
                          });
                          return false;  
                  }); 
  
                  $("#add_friend").click(function() {
                          var token = document.getElementById("friend_token").value;
                          $.ajax({
                              url : "/addfriend/", 
                              type : "POST",
                              dataType: "json", 
                              data : {
                                  csrfmiddlewaretoken: '{{ csrf_token }}',
                                  add_friend: token,
                                  },
                                  success : function(json) {
                                      document.getElementById('output').innerHTML = (json['message']);
                                  },
                                  error : function(xhr,errmsg,err) {
                                      console.log(xhr.status + ": " + xhr.responseText);
                                      document.getElementById('output').innerHTML = "Request Failed.";
                                  }
  
                          });
                          return false;  
                  }); 
  
                  $("#uppropic").click(function() {
                          var file = document.getElementById("profile_pic").files[0];
                          console.log(file);
                          $.ajax({
                              url : "profilepic/", 
                              type : "POST",
                              dataType: "json", 
                              processData: false,
                              data : {
                                  csrfmiddlewaretoken: '{{ csrf_token }}',
                                  profile_pic: file,
                                  },
                                  success : function(json) {
                                      document.getElementById('output').innerHTML = (json['message']);
                                  },
                                  error : function(xhr,errmsg,err) {
                                      console.log(xhr.status + ": " + xhr.responseText);
                                      document.getElementById('output').innerHTML = " Request Failed.";
                                  }
  
                          });
                          return false;  
                  }); 
  
  
              });
  </code></pre>
  
  <p>home.html</p>
  
  <pre><code>{% extends "base.html" %}
  {% block title %}
  {% for user in user_data %}
      {{user.username}}
  {%endfor%}
  {% endblock %}
  {% block content %}
      {% for user in user_data %}
          Username: {{user.username}}&lt;br&gt;
          First Name: {{user.first_name}}&lt;br&gt;
          Last Name: {{user.last_name}}&lt;br&gt;
          About: {{user.about}}&lt;br&gt;
          Title: {{user.title}}&lt;br&gt;
      {%endfor%}
      Friends:
      {% for friend in friend_data %}
          {{friend}}&lt;br&gt;
      {%endfor%}
              {% if is_user_profile %}
          &lt;form method='POST' &gt;
          {% csrf_token %}
          &lt;input type='text' name='friend_token' id='friend_token'&gt;
          &lt;button id='add_friend' name = 'add_friend' value='add_friend' &gt; Add Friend &lt;/button&gt;
          &lt;/form&gt;
  
          &lt;form method='POST' &gt;
          {% csrf_token %}
          &lt;button id='create_token' name = 'create_token' value='create_token' &gt; Create Token &lt;/button&gt;
          {% for user in user_data %}
          &lt;input type='hidden' id='username' value='{{user.username}}'&gt;
          {%endfor%}
          &lt;/form&gt;
  
          &lt;p id='output'&gt;
          &lt;/p&gt;
          {%endif%}
  
          &lt;form method='POST'&gt;
          {% csrf_token %}
          &lt;input type='file' name='profile_pic' id='profile_pic'&gt;
          &lt;button id='uppropic'&gt; Upload Profile Pic&lt;/button&gt;
          {% for user in user_data %}
          &lt;input type='hidden' id='username' value='{{user.username}}'&gt;
          {%endfor%}
          &lt;/form&gt;
  
      &lt;a href="/logout/"&gt;Logout&lt;/a&gt;
  {% endblock %}
  </code></pre>
  
  <p>views.py</p>
  
  <pre><code>@login_required  
  @csrf_protect       
  def upload_profilepic(request):
      context = {}
      if request.method == 'POST':
          post_data = request.POST.copy()
          profile_pic = post_data['profile_pic']
          print post_data, profile_pic
          handle_uploaded_file(request.FILES['file'])
          context.update({'message':'You must select a file to upload.'})
          return HttpResponse(simplejson.dumps(context), content_type='application/json')   
      else:
          context.update({'message':'You must select a file to upload.'})
          return HttpResponse(simplejson.dumps(context), content_type='application/json')   
  </code></pre>
  
  <p>consoleoutput</p>
  
  <pre><code>File { name: "10923328_1112855418728180_5377511192406844214_n.png", lastModified: 1421116207673, lastModifiedDate: Date 2015-01-13T02:30:07.673Z, size: 664332, type: "image/png" } home:56
  "403: 
  &lt;!DOCTYPE html&gt;
  &lt;html lang="en"&gt;
  &lt;head&gt;
    &lt;meta http-equiv="content-type" content="text/html; charset=utf-8"&gt;
    &lt;meta name="robots" content="NONE,NOARCHIVE"&gt;
    &lt;title&gt;403 Forbidden&lt;/title&gt;
    &lt;style type="text/css"&gt;
      html * { padding:0; margin:0; }
      body * { padding:10px 20px; }
      body * * { padding:0; }
      body { font:small sans-serif; background:#eee; }
      body&gt;div { border-bottom:1px solid #ddd; }
      h1 { font-weight:normal; margin-bottom:.4em; }
      h1 span { font-size:60%; color:#666; font-weight:normal; }
      #info { background:#f6f6f6; }
      #info ul { margin: 0.5em 4em; }
      #info p, #summary p { padding-top:10px; }
      #summary { background: #ffc; }
      #explanation { background:#eee; border-bottom: 0px none; }
    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;div id="summary"&gt;
    &lt;h1&gt;Forbidden &lt;span&gt;(403)&lt;/span&gt;&lt;/h1&gt;
    &lt;p&gt;CSRF verification failed. Request aborted.&lt;/p&gt;
  
  
  &lt;/div&gt;
  
  &lt;div id="info"&gt;
    &lt;h2&gt;Help&lt;/h2&gt;
  
      &lt;p&gt;Reason given for failure:&lt;/p&gt;
      &lt;pre&gt;
      CSRF token missing or incorrect.
      &lt;/pre&gt;
  
  
    &lt;p&gt;In general, this can occur when there is a genuine Cross Site Request Forgery, or when
    &lt;a
    href='http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf'&gt;Django's
    CSRF mechanism&lt;/a&gt; has not been used correctly.  For POST forms, you need to
    ensure:&lt;/p&gt;
  
    &lt;ul&gt;
      &lt;li&gt;Your browser is accepting cookies.&lt;/li&gt;
  
      &lt;li&gt;The view function uses &lt;a
      href='http://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext'&gt;&lt;code&gt;RequestContext&lt;/code&gt;&lt;/a&gt;
      for the template, instead of &lt;code&gt;Context&lt;/code&gt;.&lt;/li&gt;
  
      &lt;li&gt;In the template, there is a &lt;code&gt;{% csrf_token
      %}&lt;/code&gt; template tag inside each POST form that
      targets an internal URL.&lt;/li&gt;
  
      &lt;li&gt;If you are not using &lt;code&gt;CsrfViewMiddleware&lt;/code&gt;, then you must use
      &lt;code&gt;csrf_protect&lt;/code&gt; on any views that use the &lt;code&gt;csrf_token&lt;/code&gt;
      template tag, as well as those that accept the POST data.&lt;/li&gt;
  
    &lt;/ul&gt;
  
    &lt;p&gt;You're seeing the help section of this page because you have &lt;code&gt;DEBUG =
    True&lt;/code&gt; in your Django settings file. Change that to &lt;code&gt;False&lt;/code&gt;,
    and only the initial error message will be displayed.  &lt;/p&gt;
  
    &lt;p&gt;You can customize this page using the CSRF_FAILURE_VIEW setting.&lt;/p&gt;
  &lt;/div&gt;
  
  &lt;/body&gt;
  &lt;/html&gt;
  "
  </code></pre>
  
  <p>After doing some research the problem has to do with the way the ajax request is passing the file to django thats causing my csrf error. So I tried to follow what other people have done by appending the csrf token to formData.</p>
  
  <p>here is a stack post that has this <a href="https://stackoverflow.com/questions/16761987/jquery-post-formdata-and-csrf-token-together">JQuery: post FormData AND csrf token together</a></p>
  
  <p>The following settings are messing up the ajax request 
                                  processData: false,
                                  contentType: false,</p>
  
  <pre><code>            $("#uppropic").click(function() {
                      var file = document.getElementById("profile_pic").files[0];
                      console.log(file);
                      var csrf = '{{ csrf_token }}';
                      console.log(csrf);
                      var formData = new FormData(document.getElementById("profile_pic_form"));
                      formData.append('csrfmiddlewaretoken', csrf );
                      console.log(formData);
  
                      $.ajax({
                          url : "/profilepic/", 
                          type : "POST",
                          dataType: "json", 
                          processData: false,
                          contentType: false,
                          data : {
                              csrfmiddlewaretoken: '{{ csrf_token }}',
                              profile_pic: file,
                              },
                              success : function(json) {
                                  document.getElementById('output').innerHTML = (json['message']);
                              },
                              error : function(xhr,errmsg,err) {
                                  console.log(xhr.status + ": " + xhr.responseText);
                                  document.getElementById('output').innerHTML = " Request Failed.";
                              }
  
                      });
                      return false;  
              }); 
  </code></pre>