Suppose we have a blog post titled "Django's Book by Geeksforgeeks" with primary key id = 2. We could link to this post at
www.python.engineering/posts/2 ... Or we can refer to the title, for example
www.python.engineering/posts/The Django book by Geeksforgeeks .
But the problem space is invalid in the URL, they should be replaced with by% 20, is ugly, which makes it the following
www.python.engineering/posts/The%20Django%20book% 20by% 20pythonengineering but does not resolve the meaning of the URL. Another option could be
So the slug is now
the-django-book-by-pythonengineering . All letters are lowercase and spaces are replaced with hyphens -.
Let's assume our blog models look something like this.
Adding Slugify to our project:
Now we need to find a way to automatically convert the title to a slug.
Note. Add a new
util.py file in the same directory where you saved
M We want this script to run every time a new instance of the Post model is created. For this we will use signals.
Signals in Django:
In many cases, when there is a change in the model instance, we need to take some action. Django provides us with an elegant way to handle these situations. Signals — these are utilities that allow you to associate events with actions. We can develop a function that will run when the signal is called.
models.py file of the posts app where the Post model was defined, add it to the same file: p >
| tr> |
pre_save_receiver function must be placed separately outside the Post model.
urls.py edit the detail path with
path (& # 39; posts / & # 39 ;, detail) . In
views.py edit the detail function with
The final step is to add the link to the HTML file & lt; a href = Location / posts / layout career program a .slug} Object class being asserted = managed btn-primarytially & gt; View & lt; / a & gt ;. We are now ready to go to 127.0.0.1:8000/posts/title-you-have-added and it will show you the