Search code examples
pythondjangourlslugcanonical-link

Should I use slug field too in django URLs?


I am developing an blog like application where there are going to be posts with similar or sometimes same titles. Also users are able to edit the titles of their post whenever they want. Currently my urls look like this.

<a href="{% url 'myapp:read' post.id %}">{{post.title}} </a>

Now I've read few answers where along with id they have passed slug too like url of this question. Even with id the url is going to be unique, right? then why slug? and if it is for humanizing the url then should be store it too? So to summarize:

  1. If id is unique then why slug?
  2. If its important then should we store it?
  3. If it has anything to do with canonical-link please elaborate the working of canonical links & how slug can help it? or at least direct me to the source.

Reference: when to store slugfield in database in django? and this answer


Solution

    1. If id is unique then why slug?

    Slug is just a way for you to quickly get a sense of what this URL is about - the readability of it which is not guaranteed by only using id.

    1. If its important then should we store it?

    URL of this question could be Should I use slug field too in django URLs? and still it redirects to same post. But having said that it also depends on the implementation. In this case it could be that Stack Overflow checks for a valid slug corresponding to the post ID and if not found then redirects to the original one.

    I just changed the title of the question and as a result the URL changed as well:

    old => http://stackoverflow.com/questions/42407755/should-i-use-slug-field-too-in-django
    new => http://stackoverflow.com/questions/42407755/should-i-use-slug-field-too-in-django-urls
    

    So if you store the slug you need to make sure it is updated everytime title is changed.

    1. If it has anything to do with canonical-link please elaborate the working of canonical links & how slug can help it?

    Canonical links are used by Search Engines to identify duplicate URLs which lead to same content. YOu can view to source code of this post and you can find following canonical link in the HEAD:

    <link rel="canonical" href="http://stackoverflow.com/questions/42407755/should-i-use-slug-field-too-in-django-urls">
    

    A search engine will collect this URL and return it to you when you search for some keywords which matches this URL. One of the factors based on which the search engine ranks the pages is matching keywords in URL. A good slug helps the search engine to return the user best results based on the matched keywords in the URL.