Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a slug in Django?

I am trying to create a SlugField in Django.

I created this simple model:

from django.db import models

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()

I then do this:

>>> from mysite.books.models import Test
>>> t=Test(q="aa a a a", s="b b b b")
>>> t.s
'b b b b'
>>> t.save()
>>> t.s
'b b b b'

I was expecting b-b-b-b.

like image 217
Johnd Avatar asked Oct 05 '22 10:10

Johnd


People also ask

How do I add a slug in Django?

Adding Slugify to our project: Now we need to find a way to convert the title into a slug automatically. We want this script to be triggered every time a new instance of Post model is created. For this purpose, we will use signals. Note: Add new file util.py in the same directory where settings.py file is saved.

What is a slug field in Django?

A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They're generally used in URLs. ( as in Django docs) A slug field in Django is used to store and generate valid URLs for your dynamically created web pages.

What is a slug string?

A slug is a unique string (typically a normalized version of title or other representative string), often used as part of a URL.


1 Answers

You will need to use the slugify function.

>>> from django.template.defaultfilters import slugify
>>> slugify("b b b b")
u'b-b-b-b'
>>>

You can call slugify automatically by overriding the save method:

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()
    
    def save(self, *args, **kwargs):
        self.s = slugify(self.q)
        super(Test, self).save(*args, **kwargs)

Be aware that the above will cause your URL to change when the q field is edited, which can cause broken links. It may be preferable to generate the slug only once when you create a new object:

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()
    
    def save(self, *args, **kwargs):
        if not self.id:
            # Newly created object, so set slug
            self.s = slugify(self.q)

        super(Test, self).save(*args, **kwargs)
like image 449
Buddy Avatar answered Oct 14 '22 00:10

Buddy