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
.
In most cases the slug should not change, so you really only want to calculate it on first save:
If you're using the admin interface to add new items of your model, you can set up a
ModelAdmin
in youradmin.py
and utilizeprepopulated_fields
to automate entering of a slug:Here, when the user enters a value in the admin form for the
name
field, theslug
will be automatically populated with the correct slugifiedname
.You will need to use the slugify function.
You can call
slugify
automatically by overriding thesave
method: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: