Skip to content
Advertisement

How to auto generate slug from my Album model in django 2.0.4

I have an Album field with a list of Songs

 class Album(models.Model):
    artist = models.CharField(max_length=250)
    album_title = models.CharField(max_length=250)
    genre = models.CharField(max_length=100)
    album_logo = models.CharField(max_length=1000,blank=True)
    slug = models.SlugField(unique=True)

    def __str__(self):
        return self.album_title               

class Song(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    artist = models.CharField(max_length=250, blank=True)
    file_type = models.CharField(max_length=10)
    song_title = models.CharField(max_length=100)    

    def __str__(self):
        return self.artist

I would like to know how to generate slugs from the album title. I am following a tutorial which is using django 1.8 which uses regular expressions to implement this task. But from looking through the documentation they have introduced a more simpler approach (”). So can you help explain how I can implement it for a beginner to understand not only in this context but if possible across board. Thanks in advance.

Advertisement

Answer

Django autogenerates the slug from the string object you pass to the slug field.

# Import slugify to generate slugs from strings
from django.utils.text import slugify 

class Album(models.Model):
    artist = models.CharField(max_length=250)
    album_title = models.CharField(max_length=250)
    genre = models.CharField(max_length=100)
    album_logo = models.CharField(max_length=1000,blank=True)
    slug = models.SlugField(unique=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.album_title)
        super(Album, self).save(*args, **kwargs)

    def __str__(self):
        return self.album_title    


class Song(models.Model):
    album = models.ForeignKey(Album, on_delete=models.CASCADE)
    artist = models.CharField(max_length=250, blank=True)
    file_type = models.CharField(max_length=10)
    song_title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.song_title)
        super(Song, self).save(*args, **kwargs)    

    def __str__(self):
        return self.artist
Advertisement