Login

Automatically read the ID3 tag from a mp3 on save

Author:
sbaechler
Posted:
September 22, 2011
Language:
Python
Version:
1.3
Tags:
tag id3 mp3
Score:
0 (after 0 ratings)

This code allows you to upload a mp3 to the Admin Frontend. The ID3 tags are automatically read out and filled in to the according fields.

This should work for other filetypes as well. As long as they have an id3 tag.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from mutagen.easyid3 import EasyID3
from django.utils.translation import ugettext_lazy as _
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile


class Song(models.Model):
    file = models.FileField(_('File'), upload_to='medialibrary/songs', blank=True, null=True,
                            help_text=_('Upload an mp3 here and hit [Save and continue editing].<br />The song
                                          infos are read out automatically.'))
    artist = models.CharField(_('Artist'), max_length=50, blank=True)
    album = models.CharField(_('Album'), max_length=50, blank=True)
    title = models.CharField(_('Title'), max_length=50, blank=True)

    def clean(self):      
        if self.file:
            path = default_storage.save(os.path.join(settings.MEDIA_ROOT,'tmp','temp.mp3'),
                   ContentFile(self.file.file.read()))
            id3 = EasyID3(os.path.join(settings.MEDIA_ROOT, path))
            if not self.artist: self.artist = id3.get('artist', '')[0]
            if not self.title: self.title = id3.get('title', '')[0]
            if not self.album: self.album = id3.get('album', '')[0]
            print id3.get('artist', '')
            path = default_storage.delete(os.path.join(settings.MEDIA_ROOT,'tmp','temp.mp3'))
        super(Song, self).clean()

More like this

  1. Hyperlink read-only ForeignKey objects in admin to their change pages by strangefeatures 3 years, 4 months ago
  2. Win32 Read Registry Tag by mpa 8 years, 2 months ago
  3. Template tag for stripping blank lines by akaihola 7 years, 4 months ago
  4. Django JSONP Decorator by cominatchu 4 years, 8 months ago
  5. Group sequence into rows and columns for a TABLE by davidwtbuxton 4 years, 3 months ago

Comments

MechanisM (on October 26, 2011):

Nice snippet! How about albumart from mp3 to ImageField?

#

Please login first before commenting.