Reputation: 3452
I have this model with a clean method to validate upload of mp3 files in django admin (note the audio_file field):
class Cancion(models.Model):
nombre = models.CharField(max_length=100
,verbose_name=_("nombre"))
audio_file = models.FileField(upload_to="audio"
, verbose_name=_("audio"))
album = models.ManyToManyField("music_manager.Album"
,through="music_manager.CancionAlbum"
,through_fields=('cancion', 'album')
,verbose_name=_("canciones_albums")
,related_name="cancione_albums")
reproducciones = models.IntegerField(verbose_name=_("reproducciones")
,default=0)
playlist = models.ManyToManyField("music_manager.Playlist"
,through="music_manager.CancionPlaylist"
,through_fields=('cancion', 'playlist')
,verbose_name=_("canciones_playlist")
,related_name="cancione_playlist")
class Meta:
verbose_name_plural= "Canciones"
verbose_name = "Cancion"
# Override the __unicode__() method to return out something meaningful!
def __unicode__(self):
return self.nombre
def clean(self):
file = self.audio_file.file
print("Archivo: "+str(file))
if file:
if file._size > 20*1024*1024:
raise ValidationError(_("El archivo de audio es demasiado grande ( > 20mb )"))
if not file.content_type in ["audio/mp3"]:
raise ValidationError(_("El archvivo no es MP3"))
if not os.path.splitext(file.name)[1] in [".mp3",]:
raise ValidationError(_("El archivo no posee la extension apropiada"))
# Here we need to now to read the file and see if it's actually
# a valid audio file. I don't know what the best library is to
# to do this
return file
else:
raise ValidationError("Couldn't read uploaded file")
The clean function works well when creating a new model object. However, when changing an attribute of the object on the admin change form I get:
'File' object has no attribute '_size'
Can anyone tell me what I´m doing wrong?
Upvotes: 1
Views: 2817
Reputation: 31414
_size
is an internal Django attribute that it uses to cache the file size - it is not always set (e.g., when editing an existing object in the admin). You should not be accessing it directly.
Instead try file.size
.
Upvotes: 9