Creating a URL Shortener service in Python Django


URL shorteners have become a popular service on the web. Companies like bitly are making great fortunes from them. But sometimes when you want a custom URL you get to pay for the service. So in this tutorial I am going to show you how to build a URL shortener service in Django.

In this tutorial I expect you to be familiar with templates and forms because i wont cover them but instead i will just show you how to pragmatically build create the service in python code.


To setup the project, we shall need only one package. django-urlshortner. So lets begin by installing the package using pip. This asumes you have already setup a django project.

pip install django-urlshortner

After you should add the urlshortner app to your INSTALLED_APPS in


    # ....

Then you migrate the models to your database

python3 migrate

Lastly add the routes to your URLConf in your of your project.

url_patterns = [
    # ...
    path("r/", include("urlshortner.urls")),

Now you are good to go.


The library provides a list of utils to create shortened urls.

To create a short version of a url use the shorten_url function from urlshortner.utils module

# python3 shell
from urlshortner.utils import shorten_url

url_route = shorten_url(

# >>> 0ee3f0

You can now navigate to you the route that you assigned to urlshortner.urls in your URLConf add the returned value att the end of the url. In this case it would be http://localhost:8000/r/0ee3f0/ and this would redirect you to the right URL

Sometimes you want to create a custom URL. For example you want to create a short link for a blog about your new product and you want a url that is easy to remember. You can add this easily by adding the value argument to the shorten_url function

from urlshortner.utils import shorten_url

url_route = shorten_url(

You can now navigate to https://localhost/r/NewProduct and It will redirect you

Now that you know how to use the package i think you can intergrate it with you project.

Hope this article was helpful. You can git the project a star on Github or if you have any idea to add on you can contribute to its repository. And bythaway I am the Author of this library.

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

6 Big mistakes most beginner software engineers make 🙁 – I wish I knew this when I started programming 😢

Next Post

Going International: 15 SEO Steps for a Successful Expansion

Related Posts