sankaet sankaet -4 years ago 118
Javascript Question

URL detection and shortening in Django

I was just wondering if there is a way in Django to detect URLs from a bunch of text and then shorten them up automatically. I know I can use urlize to detect urls, but I am not sure if I can use maybe bitly or something to shorten the links.

And also would it be better to accomplish this task with javascript instead of python? and if that is the case how do I go about it?

Answer Source

For if you just want to shorten URLs, its quite simple:

First create an account, and then visit to get your API key.

Send a request to the shorten method of the API, the result is your shortened URL:

from urllib import urlencode
from urllib2 import urlopen

ACCESS_KEY = 'blahblah'
long_url = ''
endpoint = '{0}&longUrl={1}&format=txt'
req = urlencode(endpoint.format(ACCESS_KEY, long_url))
short_url = urlopen(req).read()

You can wrap that up into a template tag:

def bitlyfy(the_url):
    endpoint = '{0}&longUrl={1}&format=txt'
    req = urlencode(endpoint.format(settings.ACCESS_KEY, the_url))
    return urlopen(req).read()

Then in your template:

{% bitlyfy "" %}

Note: Positional arguments in tags are a feature of django 1.4

If you want the all the features of the API, start by reading the documentation at, and then download the official python client.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download