Table of contents
No headings in the article.
To make Django Model Field Case-Insensitive you don’t need to hack the ModelManager, Middleware or View, just follow the simple steps below:
- Install my package called "Django Case-Insensitive Field" from pypi.org using the command below:
pip install django_case_insensitive_field
- Extend CaseInsensitiveFieldMixin
I love to organize my code, so I have created a file named fields.py
file in my app directory. The content of the file is given below:
from django.db.models import CharField
from django_case_insensitive_field import CaseInsensitiveFieldMixin
class CaseInsensitiveCharField(CaseInsensitiveFieldMixin, CharField):
"""[summary]
Makes django CharField case insensitive \n
Extends both the `CaseInsensitiveMixin` and CharField \n
Then you can import
"""
def __init__(self, *args, **kwargs):
super(CaseInsensitiveMixin, self).__init__(*args, **kwargs)
- Use the CaseInsensitiveCharField in your
models.py
file:
from .fields import CaseInsensitiveCharField
class UserModel(models.Model):
username = CaseInsensitiveCharField(max_length=16, unique=True)
user1 = UserModel(username='user1')
user1.save() # will go through
user2 = UserModel(username='User1')
user2.save() # will not go through
That’s all — the simplest way to make Django Model Field case-insensitive. I hope that in the future Django will include this pacakage natively.