2013-03-04 90 views
0

我有一個Django模型,需要一個音頻文件:子類的FileField Django的REST框架

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回調對我來說尤其重要。

回答

0

我搜索如何自定義filefield,我不知道它是否解決了您的問題。如果沒有,我會再次搜索它,並告訴我錯誤。

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 
+0

謝謝,但我需要一個''serializers.FileField''的子類,可以使用''upload_to''參數或類似的東西。我編輯了這個問題,使它(希望)更清楚。 – gozzilli 2013-03-04 18:56:13

+0

好的,我會嘗試修復它 – catherine 2013-03-05 00:38:59