Login

Tag "tinyurl"

Snippet List

Create short URL redirects for site urls.

This allows you to host your own URL shortening service for your site's internal urls. By adding this class as a Mixin to your models, any model with a get_absolute_url method will have a get_short_url method also, which either returns an existing redirect or creates a new one and returns that. **Usage:** Import the class above, add the mixin to your model declaration, and ensure you have declared a get_absolute_url method. `class MyModel = (models.Model, ShortURL):` **Pre-requisites:** You must have the django.contrib.redirects app installed, and you must be using the RedirectFallbackMiddleware as a middleware class. **Settings:** Change the settings in the code above or set them in your settings.py file SHORTURL_CHARS: the characters to use when creating a shorturl SHORTURL_CHAR_NO = the number of characters to use in a shorturl SHORTURL_APPEND_SLASH = whether to append a slash to the end of the shorturl redirect **Notes:** The default settings will give you about 17 million different unique short URLs, reducing the number of characters used to 4 will give you 600,000 or so. That's enough that collisions will be quite rare for sites of a few thousand pages (collisions just result in a urls being generated until an unused combination is found) but if you've got a big site you'll probably want to explore a more robust solution with a proper hash function. [http://matt.geek.nz/blog/text/generating-short-urls-django-site-urls/](http://matt.geek.nz/blog/text/generating-short-urls-django-site-urls/)

  • url
  • redirect
  • tinyurl
  • short
Read More

3 snippets posted so far.