I have a simple blog where the post model contains a slug field that is prefilled with the post title. I would like to know how to get this slug updated in the background when the user updates a post title in the viewUpdate:
models.py
class Post(models.Model):
title = models.CharField(max_length=150)
content = models.TextField()
date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(
CustomUser,
on_delete=models.CASCADE
)
slug = models.SlugField(unique=True)
def get_absolute_url(self):
return reverse('post_detail', kwargs={'slug': self.slug})
def save(self, *args, **kwargs):
self.slug = self.slug or slugify(self.title)
super().save(*args, **kwargs)
urls.py
urlpatterns = [
path('post/<slug:slug>/', views.PostDetailView.as_view(), name='post_detail'),
]
views.py
class PostUpdateView(UpdateView):
model = Post
fields = ['title', 'content', 'tags']
I assume I should add something else to view.py in order to have the slug updated but after hours googling it, I could not find it.
Please let me know if you need more information. It is quite a simple question so I am not sure if I should provide anything else.
You can change the save
method to:
class Post(models.Model):
# …
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
That being said, it is not per se a good idea to change the slug. A slug is usually used in a URL. That thus means that if a URL for a Post
is for example bookmarked by a user, and later the title changes, then that URL will no longer work. Terefore a slug is usually something that should not be modified (often). In fact in most content management systems (CMS), the slug does not change, and you can look at the URL to see the original title of the article.