Adding A Custom Slug In Django


May 3, 2023 • Python Django



There are a couple ways to setup custom slug for your webpages. One way you can do this is by using the title you store in your database as the custom slug. Another way is to just use the database id. My recommendation is to add a new field in your models.py file called slug. This helps avoid potential issues and to make the overall look of the slug in the url looking good (for example if your title is long you could shorten the slug).

 

 

Adding The Slug To models.py

 

This part is really simple, if you have a class setup in your models.py file then all you need to do is make a new variable that will contain your slug. If you have previously setup your website and have entries into the database then make sure to add default="" to fill the newly created empty fields when you migrate. It should look something like the following.

 

slug = models.CharField(max_length=255, default="")

 

Remember after changing anything in the models field to run the python manage.py makemigration then python manage.py migrate commands in the cmd.

 

 

Updating views.py

 

Another simple addition to any views that will contain custom slugs. An example below is what your detail view for a blog could look like.

 

def blog_detail(request, slug):
    post = Post.objects.get(slug=slug)

    form = CommentForm()
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = Comment(
                author=form.cleaned_data["author"],
                body=form.cleaned_data["body"],
                post=post
            )
            comment.save()

    comments = Comment.objects.filter(post=post)
    context = {
        "post": post,
        "comments": comments,
        "form": form,
    }

 

 

Updating urls.py

 

You need to update your path for the custom slug. Depending on how you setup you urls.py file the line you will add will look something like the following.

 

path("blogpost/<str:slug>/", views.blog_detail, name="blog_detail"),

 

 

Updating Your html File For Pages That Contain The Custom Slugs

 

This step is highly dependent on how you setup your page index. Below you can find an example of how I setup mine.

 

<a href="{% url 'blog_detail' post.slug %}" class="px-4 py-3 dark:text-white bg-gray-100 hover:bg-gray-200 dark:bg-gray-600 dark:hover:bg-gray-700 duration-200 rounded-lg drop-shadow-xl">

 

After you complete the above steps you should now have custom slugs. If you had some pages setup before adding cutsom slugs, make sure to go to the admin console or if you edit through the database (not recommended), to update the slug fields.




Leave a comment:




Comments: