Search code examples
urlurl-routingslug

Implementing URL slug functionality in a website


I would like to know how to implement a URL slug functionality in a website, without having the ID of the record currently being viewed show up in the URL.

For example, StackOverflow URLs look like this: MVC Dynamic Views From Url Slug. Notice the URL contains the ID of the record. If I were to bookmark this page, and for some reason the ID of the record changed, I would not be able to look at this record in the future.

I want to implement a URL slug functionality that doesn't depend on the ID of the record, so it will look something like https://stackoverflow.com/questions/mvc-dynamic-views-from-url-slug.

Can you please provide steps for achieving this? Do you use the title of the record and sluggify it, save that slug, and never change it again?

A sample URL of what I am looking for is this http://weblogs.asp.net/scottgu/archive/2010/10/04/jquery-templates-data-link-and-globalization-accepted-as-official-jquery-plugins.aspx (Notice no ID in the URL)

Thanks!


Solution

  • That’s basically what you do. Each method has its advantages:

    • On Stack Overflow, since the title of a question can be changed, the ID is used to permanently link to the question, and URLs with an incorrect title will simply redirect.
    • Using the slug as the permanent identifier means the slug can never change. Changing the title will be possible, but it may seem confusing, and you might be better off redirecting the slug. Also, the slugs either need to be globally unique, or you need to figure out a way to enforce uniqueness for each year/month/day or whatever.

    You will need a database index to make slug lookup efficient. Fortunately, Django’s Slug field automatically creates a database index.

    You probably still want to have a numeric primary key, simply to make the rest of your database simpler.