40 - Auto Generate Slugs with Recursion - Python & Django 3.2 Tutorial Series

preview_player
Показать описание
40 - Auto Generate Slugs with Recursion - Python & Django 3.2 Tutorial Series

Try Django 3.2 is a series to teach you the fundamentals of creating web applications with Python & Django by building a real project step-by-step.

Рекомендации по теме
Комментарии
Автор

Why didn't we use:

slug = f"{slug} - {id}"

So it would be "hello-world-35" for example. Wouldn't it be more user friendly than these big numbers, and IDs are always unique if I'm not mistaken.
No offense. I'm not trying to be a smartass. I think your entire course is just great. That's how I'm studying Django. Thanks for your work man.

GennadyPodrezov
Автор

Hello! Amazing tutorial! I have a question... couldnt we just use "qs = instead of (slug=slug) to avoid double slug titles?

hfengenharia
Автор

A bit confused why slugify_instance_title() needs to be used in both pre_save and post_save.

jiweihe
Автор

In worst case you can have a slug like this: if by chance the same random number is used. Just my two cents regarding slugify. My solution to increment an existing slug correctly would be the following with adding a counter and save the initially created slug(i.e. "hello-world") to 'old_slug'. Because I don't expect hundreds of same titles in production I am okay with the number of loops.
def slugify_instance_title(instance, save=False, new_slug=None, new_counter=0, old_slug=None):
counter = new_counter
if new_slug is not None:
slug = new_slug
else:
slug = slugify(instance.title)
old_slug = slug
Klass = instance.__class__
qs =
if qs.exists():
counter += 1
slug = f"{old_slug}-{counter}"
return slugify_instance_title(instance, save=save, new_slug=slug, new_counter=counter, old_slug=old_slug)
instance.slug = slug
if save:
instance.save()
return instance

maikkusmat
Автор

I dont understand how that save=save works when it will be True, does Django do it on its own?

mariogeorgiev
Автор

Why not just use he object's/instance id at the end of the slug incase its duplicate 😩 eh omg I'm so smart

alamicrodev
Автор

def get_new_slug(instance, slug, loop=1):
if loop == 1:
qs =
else:
qs =
if qs.exists():
return get_new_slug(instance, slug, loop + 1)
return slug if loop == 1 else f"{slug}-{loop}"

def slugify_instance_title(instance, save=False):
instance.slug = get_new_slug(instance, slugify(instance.title))
if save:
instance.save()

henriquesalgueiro