title: Javascript XMLHttpRequest with Django
body: <p>I'm trying to send some photos with <code>fetch</code> using <code>React JS</code> to <code>Django</code>. And then I want to save those photos to the database using Django.</p>
  
  <p>The <code>React JS</code> function to handle sending photos is as follows:</p>
  
  <pre><code>handleAdd(e){
          e.preventDefault();
          let data = this.state.data;
          let pictures = this.state.pictures;
  
          let body = new FormData();
          body.append('data', JSON.stringify(data));
  
          if (pictures.length &gt; 0){
              _.each(pictures, (picture, i) =&gt; {
                  body.append('pictures', picture);
              });
          }    
  
          let xhr = new XMLHttpRequest();
          xhr.open('POST', `http://localhost:8000/master/api/add-inspection/`);
          xhr.setRequestHeader("Authorization", "Token vEdD9t701LtDaCZYrSEutHKSNnAuUFAV");
          xhr.onload = e =&gt; {
              if (xhr.readyState === 4) {
                  if (xhr.status === 200) {
                      console.log("Status 200");
                  } else {
                      console.log("Error");
                  }
              }
          };
          xhr.onerror = e =&gt; {
              console.log("Error " + e);
          };
          xhr.send(body);
      }
  </code></pre>
  
  <p>And then Django.</p>
  
  <p>In <code>settings.py</code> I have <code>MEDIA_ROOT</code> and <code>MEDIA_URL</code></p>
  
  <pre><code>MEDIA_URL = '/media/'
  MEDIA_ROOT = os.path.join(BASE_DIR, 'master/static/master/img/inspection_pictures'),
  STATICFILES_DIRS = (os.path.join(BASE_DIR, 'master/static/master/img/inspection_pictures'),)
  </code></pre>
  
  <p>The <code>add_inspection</code> view is as follows:</p>
  
  <pre><code>@token_required
  @transaction.atomic
  def add_inspection(request):
      if request.method == "POST":
          data = json.loads(request.POST.get('data'))
          pictures = request.FILES
  
          n_inspection = Inspection()
          n_inspection.user_id = data['user']['id']
          n_inspection.data = json.dumps(data)
          n_inspection.save()
  
          save_pictures(n_inspection, pictures)
  
          return HttpResponse("Its ok.", status=200)
      else:
          return HttpResponse("Something went wrong.", status=400)
  </code></pre>
  
  <p>Where the <code>save_pictures</code> function is as follows:</p>
  
  <pre><code>def save_pictures(inspection, pictures):
  
      print(pictures)  // Gives me &lt;MultiValueDict: {'pictures': [&lt;InMemoryUploadedFile: samsung-s8.png (image/png)&gt;, &lt;InMemoryUploadedFile: Simulator Screen Shot 6 Jul 2017, 15.43.55.png (image/png)&gt;]}&gt;
  
      for picture in pictures['pictures']:
          n_picture = InspectionPictures()
          n_picture.inspection_id = inspection.id
          n_picture.picture = picture
  
          print(picture) // first iteration : b'\x89PNG\r\n'
  
          n_picture.save()
  </code></pre>
  
  <p>Thus, it seems that everything works perfect.</p>
  
  <p><code>InspectionPictures</code> model is as follows:</p>
  
  <pre><code>def inspection_picture_path(self, filename):
      return 'inspection_{0}/{1}'.format(self.inspection.id, filename)
  
  
  class InspectionPictures(models.Model):
      inspection = models.ForeignKey(Inspection, on_delete=models.CASCADE)
      picture = models.FileField(upload_to=inspection_picture_path, blank=True)
  
      def __str__(self):
          return "Inspection-{}".format(self.inspection.id)
  </code></pre>
  
  <p>But when it needs to save the photo (<code>n_picture.save()</code>) I get <strong>INTERNAL SERVER ERROR</strong> (<strong>AttributeError: 'bytes' object has no attribute '_committed'</strong>)</p>
  
  <p>The whole error is as follows:</p>
  
  <blockquote>
    <p>Internal Server Error: /master/api/add-inspection/
    Traceback (most recent call last):
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 39, in inner
        response = get_response(request)
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
        return view_func(*args, **kwargs)
      File "/Users/boris/Projects/car_inspection/car_inspection/api/authentication.py", line 71, in _view
        return view_func(request, *args, **kwargs)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py", line 53, in inner
        return func(*args, **kwds)
      File "/Users/boris/Projects/car_inspection/car_inspection/api/views.py", line 29, in add_inspection
        save_pictures(n_inspection, pictures)
      File "/Users/boris/Projects/car_inspection/car_inspection/api/views.py", line 47, in save_pictures
        n_picture.save()
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/db/models/base.py", line 796, in save
        force_update=force_update, update_fields=update_fields)
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/db/models/base.py", line 824, in save_base
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _save_table
        result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/db/models/base.py", line 947, in _do_insert
        using=using, raw=raw)
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
        return getattr(self.get_queryset(), name)(*args, **kwargs)
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/db/models/query.py", line 1045, in _insert
        return query.get_compiler(using=using).execute_sql(return_id)
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1053, in execute_sql
        for sql, params in self.as_sql():
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1006, in as_sql
        for obj in self.query.objs
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1006, in 
        for obj in self.query.objs
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1005, in 
        [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 955, in pre_save_val
        return field.pre_save(obj, add=True)
      File "/Users/boris/Projects/car_inspection/venv/lib/python3.6/site-packages/django/db/models/fields/files.py", line 290, in pre_save
        if file and not file._committed:
    AttributeError: 'bytes' object has no attribute '_committed'</p>
  </blockquote>