Sudeep's Blog

URL Shortener with Django (Part 4) - Working with Urls and views

Now we will be working with our actual URLs and Views of our site.

Open up your “urlshortener/” and add the following code to it:


from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    url(r'^admin/', include(,
    # if the URL pattern match /admin/ then open up admin panel

    url(r'', include('shortenersite.urls',
    # if anything rather then /admin/ then it will look for shortenersite/urls

Next, create a new file ‘’ inside shortenersite. And add the following code.


from django.conf.urls import patterns, include, url

urlpatterns = patterns('shortenersite.views',
    url(r'^$', 'index', name='home'),
    # for our home/index page

    url(r'^(?P<short_id>\w{6})$', 'redirect_original', name='redirectoriginal'),
    # when short URL is requested it redirects to original URL

    url(r'^makeshort/$', 'shorten_url', name='shortenurl'),
    # this will create a URL's short id and return the short URL

Now we are done with our URLs now let us create views. But before that add these lines to your file.


SITE_URL = "http://localhost:8000"

We will need this because while generating the short URL which looks like SITE_URL can be different in different cases. Normally it is the URL of the website where this project is hosted on.

Now open up your “shortenersite/” and add the following code.


from django.shortcuts import render_to_response, get_object_or_404
import random, string, json
from shortenersite.models import Urls
from django.http import HttpResponseRedirect, HttpResponse
from django.conf import settings
from django.core.context_processors import csrf

def index(request):
    c = {}
    return render_to_response('shortenersite/index.html', c)

def redirect_original(request, short_id):
    url = get_object_or_404(Urls, pk=short_id) # get object, if not        found return 404 error
    url.count += 1
    return HttpResponseRedirect(url.httpurl)

def shorten_url(request):
    url = request.POST.get("url", '')
    if not (url == ''):
        short_id = get_short_code()
        b = Urls(httpurl=url, short_id=short_id)

        response_data = {}
        response_data['url'] = settings.SITE_URL + "/" + short_id
        return HttpResponse(json.dumps(response_data),  content_type="application/json")
    return HttpResponse(json.dumps({"error": "error occurs"}), content_type="application/json")

def get_short_code():
    length = 6
    char = string.ascii_uppercase + string.digits + string.ascii_lowercase
    # if the randomly generated short_id is used then generate next
    while True:
        short_id = ''.join(random.choice(char) for x in range(length))
            temp = Urls.objects.get(pk=short_id)
            return short_id

Let’s talk about what the above views does.

index : It opens the index page by rendering the template.

redirect_original : It redirects short URL to it’s original URL.

shorten_url : We will make a request to this view to create and return us the short URL.

get_short_code : This will generate the unique short code/id for URLs.

So, this is the end of the part 4. At this moment this app do not work so have a patience and move to next part. In the next part we will add our template and static files and finish up our project.

Post Series:

Part 1: Create a virtual environment and install Django

Part 2: Create a new project and make sure it works

Part 3: Create Django App, Model for our App and work with Django Admin

Part 4: Working with URLs and Views

Part 5: Working on Templates, Static files and finishing up