Easy Case-insensitive Usernames for Postgres (Email or Username)


Thought some people here might find this useful. I know implementing case-insensitive usernames (email or username) is pretty important for quite a few applications. Thankfully the Django team has leveraged a great Postgres-specific field called CIText, which allows you to store text as case-sensitive (so case-sensitive emails will remain / be stored as same case as inputed), but it matches in a case insensitive way, such that users can log in with case-insensitive email (e.g. John.Doe@gmail.com or john.doe@gmail.com, both work) and also there’s a uniqueness such that if John.Doe@gmail.com is already registered, then john.doe@gmail.com cannot be registered. It’s truly brilliant and easy.

So if you’re using postgres and want case-insensitive emails or usernames, just add the citext extension to postgres:
e.g. in psql:


then in your user’s models.py:

from django.contrib.postgres.fields.citext import CIEmailField, CICharField

username = CICharField(unique=True, max_length=30)
email = CIEmailField(unique=True, max_length=75)

And it just works without any other wrangling.


(Vitor Freitas) #2

That’s super cool! I didn’t know about those CI fields. Thanks for sharing it!

It’s always good to add those constraints at database level.

I think it would be possible to automate the create extension step using a data migration :+1: