How do I create a slug in Django

+1 vote

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.

Jun 26, 2020 in Python by kartik
• 37,510 points
1,062 views

1 answer to this question.

0 votes

Hello @kartik,

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.

Hope it helps!!

Thanks!!

answered Jun 26, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

How do I create a dataframe using a dictionary in pandas?

Hi @Hannah, You need to define your dictionary ...READ MORE

answered Nov 18, 2019 in Python by Eric
602 views
0 votes
1 answer

How do I make a field readonly (or disabled) so that it cannot be edited in Django form?

Hello @kartik, Setting readonly on a widget only makes the ...READ MORE

answered Aug 6, 2020 in Python by Niroj
• 82,880 points
15,918 views
0 votes
1 answer

How do I create a constant in Python?

Hello @kartik, No there is not. You cannot ...READ MORE

answered Nov 19, 2020 in Python by Niroj
• 82,880 points
1,183 views
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,440 points
975 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
2,091 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
1,239 views
+1 vote
1 answer

How do I return JSON without using a template in Django?

Hello @kartik, In the case of the JSON ...READ MORE

answered Jul 3, 2020 in Python by Niroj
• 82,880 points
4,562 views
0 votes
1 answer

How do I do a not equal in Django queryset filtering?

Hello @kartik, Try this code below: >>> from myapp.models ...READ MORE

answered Jul 3, 2020 in Python by Niroj
• 82,880 points
4,411 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP