Django Slug Tutorial: Readable URLs
Aug 03, 2020 | 644 views
Refer to
- django-slug-tutorial
- #django.utils.text.slugify
- Generating slugs automatically in Django without packages - Two easy and solid approaches (added on 2020/8/5)
urls.py
urlpatterns = [
path('post/<str:slug>', views.post_detail, name='post_detail'),
]
The code refer from https://github.com/Radi85/django-website.git, under its section blog/models.py:
class Post(models.Model):
...
slug = models.SlugField(max_length=200, null=False, unique=True,
blank=True, verbose_name="Slug (Not required)")
def set_slug(self):
if not self.slug:
# if Post.objects.filter(slug__isnull=True):
# Newly created object, so set slug
_title = self.title
unique_slug = self.slug = slugify(_title, allow_unicode=True)
count = 1
# Keep checking if the new generated slug exists
while Post.objects.filter(slug=unique_slug).exists():
unique_slug = "{}-{}".format(self.slug, count)
count += 1
self.slug = unique_slug
def save(self, *args, **kwargs):
self.set_slug()
super(Post, self).save(*args, **kwargs)
Comments: 1