title: Django uploads: Discard uploaded duplicates, use existing file (md5 based check)
body: <p>I have a model with a <code>FileField</code>, which holds user uploaded files. Since I want to save space, I would like to avoid duplicates.</p>
  
  <p><strong>What I'd like to achieve:</strong></p>
  
  <ol>
  <li><strong>Calculate</strong> the uploaded files <strong>md5 checksum</strong></li>
  <li>Store the file with the <strong>file name based on its md5sum</strong></li>
  <li>If a file with that name is already there (the new file's a <strong>duplicate</strong>), <strong>discard the uploaded file and use the existing file instead</strong></li>
  </ol>
  
  <p><strong>1</strong> and <strong>2</strong> is already working, but <strong>how would I forget about an uploaded duplicate and use the existing file instead?</strong></p>
  
  <p>Note that I'd like to <em>keep the existing file</em> and <em>not</em> overwrite it (mainly to keep the modified time the same - better for backup).</p>
  
  <p><strong>Notes:</strong></p>
  
  <ul>
  <li>I'm using Django 1.5</li>
  <li>The upload handler is <code>django.core.files.uploadhandler.TemporaryFileUploadHandler</code></li>
  </ul>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>def media_file_name(instance, filename):
      h = instance.md5sum
      basename, ext = os.path.splitext(filename)
      return os.path.join('mediafiles', h[0:1], h[1:2], h + ext.lower())
  
  class Media(models.Model):
      orig_file = models.FileField(upload_to=media_file_name)
      md5sum = models.CharField(max_length=36)
      ...
  
      def save(self, *args, **kwargs):
              if not self.pk:  # file is new
                  md5 = hashlib.md5()
                  for chunk in self.orig_file.chunks():
                      md5.update(chunk)
                  self.md5sum = md5.hexdigest()
              super(Media, self).save(*args, **kwargs)
  </code></pre>
  
  <p>Any help is appreciated!</p>