Django Tutorial – Building URL Shortener with Django

I finally got the time to write a Django tutorial. In this tutorial we are building URL Shortener. If you are confused with what we are building then we are building something similar to (bit.ly) or (goo.gl).

We are building the app that will make a shorter URL of a longer URL. (Example) Normally the shorter URL will be localhost:8000/4hh5kr for http://www.facebook.com

I am using Django 1.7.1 with Python 3.3.2+. Don’t worry if you have different version of Django because we will set up our virtual environment and install latest version of Django. But be sure you do have Python 3+ because installing Python will not be covered in this tutorial.

I assume that you have completed Writing your first Django app. It is not really essential to complete this tutorial but it is highly recommended that you complete this tutorial before we begin. It will give you a lot of knowledge that will be useful in this tutorial.

You can also get the source code of this app in Github(django_urlshortener).

This tutorial is divided into 5 parts:

Well let’s start to build our URL Shortener then.

Part 1, Create a virtual environment and install Django

Let us start by creating a virtual environment and installing Django. So, open up your Terminal and follow the instruction below.

Create a new folder for our project.

$ mkdir tutorial

Go inside the tutorial folder (folder we just created)

$ cd tutorial

Create virtual environment with python 3.

$ virtualenv -p /usr/bin/python3 py3env

Activate our virtual environment py3env.

$ source py3env/bin/activate

(Note: To deactivate it you can just use “deactivate” but now don’t deactivate it.)

Run the following command to install Django:

$ pip install Django==1.7.1

Depending on your Internet speed, it may take some minute or less than a minute.

After done, let us check that Django is really installed.

To check the version of Django installed, enter the following command:

$ python -c 'import django; print(django.get_version())'

You must see something similar to the following:
check_Django_version

So, this is the end of the first part. We set up our virtual environment and installed Django. Now you are ready to move to next part.

Before moving to Part 2, from now whenever you follow this tutorial don’t forget to activate virtual environment (py3env) or things may go little wired.

17 thoughts on “Django Tutorial – Building URL Shortener with Django

  1. Instead of settings.SITE_URL you can use ‘reverse’ with your redirectOriginal URL. Then you don’t need to change settings.py for different sites.

    Like

  2. Your use of CamelCase for function, directory and file names is inconsistent with standard Python naming patterns (see PEP-8).

    Like

  3. The current example will create a new record each time an url is submitted, code below returns the previous shortcode if a url is re-submitted :

    def shortenUrl(request):
    url = request.POST.get(“url”, ”)
    print url
    try:
    urll = Urls.objects.get(httpurl=url)
    short_id = urll.short_id
    except (Urls.DoesNotExist):
    print “Does not exist”
    if not (url == ”):
    print “URL not empty !”
    short_id = getShortCode()
    print “Got shortcode”
    b = Urls(httpurl=url, short_id=short_id)
    b.save()
    print “Saved URL”
    response_data = {}
    response_data[‘url’] = “/” + short_id
    else:
    return HttpResponse(json.dumps({“error”: “error occurs”}),content_type=”application/json”)
    response_data = {}
    response_data[‘url’] = “/” + short_id
    return HttpResponse(json.dumps(response_data), content_type=”application/json”)

    Like

    1. Actually it is useful for tracking purpose if the new shortcode is generated for URL, even same URL is submitted twice.

      Anyway you can also implement in that way.

      Like

  4. Sir,
    When i run this code there is an error on base.html tells that
    //–
    Error during template rendering

    In template /home/jobi/Recursive/django/tutorial/urlShortner/shortenerSite/templates/shortenerSite/base.html, error at line 40
    u’shortenerSite’ is not a registered namespace
    –//
    please help me to solve it

    Like

  5. My site doesn’t display the short URL that’s created. (it does create the short URL though) and also doesn’t display any warning for empty addresses. Rest everything works well.

    Like

  6. Hey there found your tut online. A couple of things there are some changes in Django 1.10 and beyond with a few things, and I downgraded to 1.7x like you have here and i’m having an issue with a traceback stating:

    “^(?P<short_id>\w{6})$” is not a valid regular expression: unknown specifier: ?P&

    Seems that when I open shortenersite/urls.py and comment out the redirection url everything works accept the re-direct is there something up there?

    Like

      1. Hey that was the ticket, must have been an issue with the code in the form on your wordpress site. Thanks Sudeep! Might also be cool to refresh this with Django 1.10 cause some things changed which breaks your tutorial. 🙂

        -adam

        Like

  7. It would be quicker to check for existence of the DB record, rather than retrieve it fully. `if not Url.objects.filter(pk=short_id).exists(): return short_id` 🙂

    Like

  8. First of all thanks for this great tutorial. I want to add in the project that if all 6 digits end then the length to get increment by 1. Can you help to come over this.Thanks in advance.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.