5

How can I add audio and video file fields in Django which accepts only the particular files?

Kindly explain me with 1 example.

models.py:

class Post(models.Model):
     audio_file = models.FileField(upload_to = u'mp3/', max_length=200)
     video_file = models.FileField(upload_to = u'video/', max_length=200)

forms.py

class PostForm(forms.Form):
     audio_file = forms.FileField( label = _(u"Audio File" ))
     video_file = forms.FileField( label = _(u"Video File" ))
Abijith Mg
  • 2,647
  • 21
  • 35
Raji
  • 551
  • 1
  • 10
  • 23

2 Answers2

4

You can simply check it through Form's clean method

class FileUploadForm( forms.Form ):
    audio_file = forms.FileField( label = _(u"Audio File" ))
    ...

def clean( self ): 
    cleaned_data = self.cleaned_data
    file = cleaned_data.get( "audio_file" )
    file_exts = ('.mp3', ) 

    if file is None:

        raise forms.ValidationError( 'Please select file first ' ) 

    if not file.content_type in settings.UPLOAD_AUDIO_TYPE: #UPLOAD_AUDIO_TYPE contains mime types of required file

        raise forms.ValidationError( 'Audio accepted only in: %s' % ' '.join( file_exts ) ) 


    return cleaned_data
Ahsan
  • 11,516
  • 12
  • 52
  • 79
2

May be these links will help you:

Only accept a certain file type in FileField, server-side

https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#uploadedfile-objects

Community
  • 1
  • 1
Tejas Patil
  • 6,149
  • 1
  • 23
  • 38