Nov 15, 2026 · 41 min read
From 2013 to Django 6.1: modernizing a URL shortener with AI
How a 2013 Django app became a library on PyPI: choosing short codes (Base62, random, HMAC), what they protect and what they don't, handling collisions, and what turns an app into a reusable package.

Django Simple URL Shortener started in November 2013 as a plain Django project: a form to shorten links, optional login and a redirect view. Its requirements.txt had two lines: Django==1.6 and python-memcached==1.53. The last relevant change of that era came in December 2016, a contribution by Samuel Dias adding Windows support and Django 1.10.
Then the code sat untouched for almost ten years. In November 2026 it was modernized in two pull requests, with commits that list GitHub Copilot as co-author. The result is a reusable Django app, published on PyPI, with declared support for Python 3.12–3.15 and Django 6.1.x, plus a demo project.
Updating a project like this is more than bumping version numbers. Much of the 2013 code relied on APIs that no longer exist (django.core.urlresolvers, __unicode__, is_authenticated() as a method, ForeignKey without on_delete). But the interesting decisions weren't about syntax. They came down to three questions: how to generate short codes, what those codes protect (and what they don't), and what it takes for an app to become something other people install in their own projects.
What the original code looked like
The heart of the 2013 project fit in a few lines. The short code was the database ID converted to base 62:
def num_to_base62(n):
if (n >= 62):
return num_to_base62(int(n / 62.)) + CHARS[n % 62]
else:
return CHARS[n]
And the model wrote the code after saving the row, because only then does the ID exist:
def save(self, *args, **kwargs):
super(Url, self).save(*args, **kwargs)
Url.objects.filter(id=self.id).update(
short_code=num_to_base62(self.id)
)
self.short_code = num_to_base62(self.id)
It worked, but on implicit assumptions: short_code had an index but no uniqueness constraint; the code was recomputed on every save(); and the conversion used floating-point division (n / 62.), which loses precision for large integers. None of these assumptions were written down, and the tests of the time only covered the happy path.
The core decision: how to generate short codes
The modernized version turns code generation into an explicit contract. Instead of a fixed function, there's an abstract class:
class UrlCodeEncoder(ABC):
"""Contract for converting a saved URL's integer primary key to a short code."""
@abstractmethod
def encode(self, value: int) -> str:
"""Return a URL-safe code for a non-negative integer."""
The host project picks an implementation with the URLSHORTENER_CODE_ENCODER setting, a dotted Python path. The app ships four implementations, each solving a different problem.
Switching strategies is one line in the host project's settings.py:
# settings.py URLSHORTENER_CODE_ENCODER = "urlshortener.converter.RandomUrlCodeEncoder" # or "urlshortener.converter.HmacUrlCodeEncoder" # or "urlshortener.converter.ShortHmacUrlCodeEncoder" # default: "urlshortener.converter.Base62UrlCodeEncoder"
A custom encoder is just a subclass with one method. The example from the docs:
# myproject/url_codes.py
from urlshortener.converter import UrlCodeEncoder
class HexUrlCodeEncoder(UrlCodeEncoder):
def encode(self, value: int) -> str:
if value < 0:
raise ValueError("value must be non-negative")
return f"x{value:x}"
# settings.py URLSHORTENER_CODE_ENCODER = "myproject.url_codes.HexUrlCodeEncoder"
Base62 over the ID (default)
Base62UrlCodeEncoder keeps the original behavior: the integer ID becomes a code in the 0-9a-zA-Z alphabet. ID 61 becomes Z; 62 becomes 10.
Strengths: very short codes (at most two characters up to ID 3,843), deterministic and collision-free among themselves, since every ID is unique.
Limits: it's a reversible base conversion, not encryption. There's no secret involved. Anyone can decode a code to get the ID, or go the other way: walk 1, 2, 3... and visit every link ever created. It also roughly reveals how many links the service holds.
One detail of the modernization shows care for existing links: the alphabet order (digits, then lowercase, then uppercase) was preserved, with a dedicated test. Changing it would break the mapping between codes already handed out and IDs in the database. The function was also rewritten with integer divmod, and another test checks that 62**30 encodes without going through floating point.
The current version, with no recursion and no floating point:
def num_to_base62(number: int) -> str:
"""Encode a non-negative integer as a base-62 string."""
if number < 0:
raise ValueError("number must be non-negative")
if number == 0:
return CHARS[0]
encoded: list[str] = []
while number:
number, remainder = divmod(number, len(CHARS))
encoded.append(CHARS[remainder])
return "".join(reversed(encoded))
Random codes
RandomUrlCodeEncoder ignores the ID and draws 16 characters from the same alphabet using Python's secrets module, a cryptographically secure source. That's 16 × log₂(62) ≈ 95 bits of randomness.
class RandomUrlCodeEncoder(UrlCodeEncoder):
def encode(self, value: int) -> str:
return "".join(secrets.choice(CHARS) for _ in range(RANDOM_CODE_LENGTH))
Strengths: codes follow no sequence. You can't enumerate links or infer the service's volume from a code.
Limits: codes are much longer and, being random, collisions are possible in principle. At 95 bits they're unlikely, but "unlikely" isn't "impossible", and the system has to handle the case.
HMAC codes
HmacUrlCodeEncoder computes an HMAC-SHA256 of the ID with Django's SECRET_KEY, truncates it to 128 bits and encodes it in base 62 at a fixed width of 22 characters, the minimum to represent 128 bits in that alphabet (⌈128 / log₂ 62⌉ = 22).
The core of the implementation:
message = f"urlshortener:{value}:{self._collision_counter}".encode("ascii")
self._collision_counter += 1
digest = hmac.new(
secret_key.encode("utf-8"),
message,
hashlib.sha256,
).digest()[:HASH_CODE_BYTES] # 16 bytes = 128 bits
number = int.from_bytes(digest, byteorder="big")
return num_to_base62(number).rjust(self.code_length, CHARS[0])
Strengths: the code is stable for the same ID and secret, and without the secret you can't derive a code from an ID or brute-force it in practical time.
Limits: the protection depends entirely on SECRET_KEY. If it leaks, codes become computable from IDs again. Rotating the secret only affects codes generated afterwards; saved codes stay in the database.
There's also ShortHmacUrlCodeEncoder, with 8 characters (about 47.6 bits). The docs describe it as intentionally weaker: it's for people who want short codes without Base62's obvious sequence, but it shouldn't be used where guessing or enumerating links could expose sensitive destinations. In a space that size, collisions stop being theoretical: by the birthday paradox, around 17 million links the chance of at least one collision passes 50%.
Comparing the options
| Encoder | Length | Predictable from the ID? | Needs a secret? | Collisions |
|---|---|---|---|---|
| Base62 (default) | grows with the ID | Yes, it's reversible | No | None among themselves |
| Random | 16 chars (~95 bits) | No | No | Possible, very unlikely |
| HMAC | 22 chars (128 bits) | Only with SECRET_KEY | Yes | Possible, very unlikely |
| Short HMAC | 8 chars (~47.6 bits) | Only with SECRET_KEY | Yes | Likely at high volume |
What a short code protects, and what it doesn't
The most important lesson of the project is in the docs, and worth repeating: a short link is a bearer link. Whoever has it can use it. That holds for every encoder.
So "is this encoder secure?" only makes sense with "against which risk?":
- Against enumeration (someone walking codes in sequence to discover every link): Base62 doesn't protect; random codes and 128-bit HMAC make it impractical; short HMAC offers much less.
- Against volume inference (learning how many links exist): same answer.
- Against someone who already has the link (a forwarded email, a screenshot, browser history): no encoder protects. The code isn't a password, an authentication token or access control. If the destination is private, the protection has to live at the destination.
The app reflects this: login associates links with a user and lists them with pagination, but redirects are public. Anyone with the code gets redirected, logged in or not.
Another decision consistent with this model is the permanent redirect (HTTP 301). A 301 tells browsers and intermediaries they may remember the destination. That fits codes that don't change: the model keeps the existing short_code when a row is updated, and the app's views don't offer destination editing. The other side of the trade-off is that if the product ever needs to retarget a link already in circulation, the 301 works against it.
Collisions: where reliability actually lives
Making the encoder pluggable creates a problem: the app no longer controls what encode() returns. A custom implementation could return an invalid code, or one that already belongs to another URL. The answer was to split responsibility into three layers.
1. The contract is validated. Before writing, the model checks that the result is a non-empty ASCII alphanumeric string of at most 22 characters. If not, it raises ImproperlyConfigured, and since everything runs inside transaction.atomic(), the new URL is rolled back. A test confirms it: with an encoder returning "invalid-code", no row is left behind.
2. The database enforces uniqueness. The field became unique=True. Here's a migration detail that's easy to get wrong: old rows could have an empty short_code (""), and several empty strings would violate the constraint. Migration 0002 makes the field nullable, converts "" to NULL and only then applies unique (databases like SQLite and PostgreSQL don't treat two NULLs as equal under unique constraints). That also covers the gap between the INSERT and writing the code, when the row exists but has no code yet. A third migration raised the limit from 20 to 22 characters to fit the full HMAC.
3. Collisions are retried. The code is written with an UPDATE inside a savepoint. If the database raises IntegrityError and the code belongs to another URL, the model asks the encoder for a new one, up to five attempts. If all fail, the operation aborts with an error instead of overwriting another URL's code.
for _ in range(MAX_CODE_GENERATION_ATTEMPTS):
short_code = encoder.encode(self.pk)
# ... contract validation ...
try:
with transaction.atomic():
Url.objects.filter(pk=self.pk).update(short_code=short_code)
except IntegrityError:
if Url.objects.filter(short_code=short_code).exclude(pk=self.pk).exists():
continue
raise
self.short_code = short_code
return
A subtle point: retrying only helps if the encoder can return something different on the next call. The random encoder does so naturally. HMAC is deterministic, so the implementation includes an internal counter in the signed message (urlshortener:{id}:{attempt}): the first attempt is stable for a given ID, and later ones yield new codes. A purely deterministic encoder, like Base62 or the hex example in the docs, would return the same code all five times. For those, the real guarantee is the database constraint: saving fails explicitly instead of corrupting data. That matters, for instance, when switching encoders on a database that already holds links in another format.
The check after IntegrityError is deliberate too. The error is only treated as a collision if another row actually has that code; any other integrity violation is re-raised instead of being swallowed as if it were a collision.
From app to library: tests, docs and packaging
The 2013 project was a Django site. To become something people install with pip install django-simple-url-shortner and add to INSTALLED_APPS, several small changes were needed, each removing an assumption about the host project:
- Configurable user model: the
ForeignKeypoints tosettings.AUTH_USER_MODEL, notdjango.contrib.auth.models.User, so projects with a custom user can use the app. - Namespaced static files: the original Bootstrap 3 was replaced with Bootstrap 5.3.9, bundled locally under
static/urlshortener/, with its MIT license shipped in the package. The namespace avoids clashing with the host project's static files. - App and demo separated: the published package contains only
urlshortener; thesimple_url_shortnerproject is for development and demos.pyproject.tomldeclares templates, static files and thepy.typedmarker as package data. - Environment-based config in the demo:
DJANGO_DEBUG,DJANGO_SECRET_KEY,DJANGO_ALLOWED_HOSTSandDJANGO_DB_PATH, with an explicit warning that development settings are not a production configuration.
On the installing side, integration is the same as any Django app:
python -m pip install django-simple-url-shortner
# settings.py
INSTALLED_APPS = [
# ...
"urlshortener",
]
# urls.py
from django.urls import include, path
urlpatterns = [
path("", include("urlshortener.urls")),
]
The tests cover the layers that matter to anyone depending on the package: unit tests for the converter (base-62 boundaries, zero, negatives, large integers), model tests (configured encoder, distinct random codes, a collision retry simulated with mock, rollback on invalid output) and view integration tests (anonymous and authenticated creation, 301, 404, registration, and logout now requiring POST, as in current Django). On top of that, a Playwright script starts an isolated server, creates and follows a link in Chromium and produces the screenshots used in the README.
The collision test, for example, forces the encoder to return an already-used code first and checks that the second one is what gets saved:
def test_short_code_collision_is_retried(self):
first = Url.objects.create(original_url="https://example.com/first")
with patch("urlshortener.models.get_url_code_encoder") as get_encoder:
get_encoder.return_value.encode.side_effect = [
first.short_code,
"uniqueCode",
]
second = Url.objects.create(original_url="https://example.com/second")
self.assertEqual(second.short_code, "uniqueCode")
self.assertEqual(Url.objects.count(), 2)
CI runs Ruff lint and formatting, mypy type checks (with disallow_untyped_defs), the tests with coverage and a package build with twine check on Python 3.12, 3.13, 3.14 and 3.15. There's also a Playwright job and a Windows job, which keeps alive the compatibility introduced by the 2016 contribution.
Documentation acts as the public contract. The README doesn't just say how to configure each encoder; it says when not to use each one, explains that Base62 isn't encryption and repeats that a short code isn't access control. For a library, that part matters as much as the code: people installing the package won't read converter.py before deciding.
The README also records a scope decision: AI integrations aren't part of the core package. If an MCP interface is added, it should be an optional adapter over the same operations, not a required dependency of the Django app.
Takeaways for other projects
Turn implicit assumptions into contracts. The 2013 code assumed codes were unique because IDs are unique. Once generation became pluggable, that assumption had to become a documented interface, a model-level validation and a database constraint.
Uniqueness belongs to the database. Checking "does this code exist?" before writing leaves room for race conditions. The unique constraint and IntegrityError handling provide the guarantee; application logic only decides what to do when it's violated.
Retries need variation. Retrying with the same input yields the same output. If your flow depends on retries, make sure the generator can produce something different, or that failure is explicit.
Name the risk before saying "secure". Base62 is great for short codes and terrible against enumeration. Random and HMAC codes solve enumeration, but none of them solves the link itself leaking. Each choice protects against something specific, and the docs need to say what.
Preserve what's already out there. Short links live outside the system: in emails, PDFs, print. Keeping the alphabet order, not recomputing existing codes and migrating old data carefully are low-visibility decisions, but they're what keeps links in the wild from breaking.
When modernizing with AI, the safety net is what lets you trust the result. Tests that pin the old behavior, strict typing, CI across versions and manual review before merge (required by the README itself) are what make a large change verifiable, whether a person wrote it or a tool helped.
The code, docs and tests are in the project repository, and the package is on PyPI.