Processing file uploads before object is saved

后端 未结 3 1412
情书的邮戳
情书的邮戳 2020-12-30 16:17

I\'ve got a model like this:

class Talk(BaseModel):
  title        = models.CharField(max_length=200)
  mp3          = models.FileField(upload_to = u\'talks/         


        
3条回答
  •  臣服心动
    2020-12-30 17:07

    You could follow the technique used by ImageField where it validates the file header and then seeks back to the start of the file.

    class ImageField(FileField):
        # ...    
        def to_python(self, data):
            f = super(ImageField, self).to_python(data)
            # ...
            # We need to get a file object for Pillow. We might have a path or we might
            # have to read the data into memory.
            if hasattr(data, 'temporary_file_path'):
                file = data.temporary_file_path()
            else:
                if hasattr(data, 'read'):
                    file = BytesIO(data.read())
                else:
                    file = BytesIO(data['content'])
    
            try:
                # ...
            except Exception:
                # Pillow doesn't recognize it as an image.
                six.reraise(ValidationError, ValidationError(
                    self.error_messages['invalid_image'],
                    code='invalid_image',
                ), sys.exc_info()[2])
            if hasattr(f, 'seek') and callable(f.seek):
                f.seek(0)
            return f
    

提交回复
热议问题