0

我有一个带有音频文件的 django 模型:

class Thing(models.Model):

    audio_file = AudioFileField(    upload_to=audio_dir, blank=True, null=True )
    photo_file = models.ImageField( upload_to=img_dir,   blank=True, null=True )
    ...

其中是执行一些验证AudioFileField的子类:FileField

class AudioFileField(models.FileField):
    def validate(self, value, model_instance):
        try:
            if not (value.file.content_type == "audio/x-wav" or 
                    value.file.content_type == "audio/amr" or 
                    value.file.content_type == "video/3gpp"):
                raise ValidationError(u'%s is not an audio file' % value)
        except IOError:
            logger.warning("no audio file given")

audio_dir回调设置路径并重命名文件:

def audio_dir(instance, filename):
        return os.path.join("audio", "recording_%s%s" % (
            datetime.datetime.now().isoformat().replace(":", "-"), 
            os.path.splitext(filename)[1].lower() ))

在 Django REST 框架中ImageField工作正常,但子类AudioFileField没有。这是因为子类serializers.FileField不接受关键字参数upload_to

如何通过 API 公开相同的功能?audio_dir回调对我来说特别重要。

4

1 回答 1

0

I search how to customize filefield and I don't know if it's fix your problem. If not I will search again for it and just tell me the error.

class Thing(models.Model):
    audio_file = AudioFileField(
        upload_to=audio_dir, 
        blank=True, null=True,
        content_types=['audio/x-wav', 'audio/amr', 'video/3gpp'] 
    )

    ...............

class AudioFileField(models.FileField):
    def __init__(self, *args, **kwargs):
        self.content_types = kwargs.pop("content_types")

        super(AudioFileField, self).__init__(*args, **kwargs)

    def clean(self, *args, **kwargs):        
        data = super(AudioFileField, self).clean(*args, **kwargs)

        audio_file = data.audio_file
        try:
            content_type = audio_file.content_type
            if content_type in self.content_types:
                raise ValidationError(u'{0} is not an audio file'.format(content_type))
            else:
                raise forms.ValidationError(_('Audio file type not supported.'))
        except AttributeError:
            pass        

        return data
于 2013-03-04T18:38:13.820 回答