Skip to content Skip to sidebar Skip to footer

How To Implement Django Case Insensitive Model Field?

Django do not come with case insensitive model field so how do I make a model field case insensitive without breaking my existing codes? For example: I have a username field on my

Solution 1:

There a lot of approaches to solve this problem but I will recommend using django-case-insensitive-field from pypi.org.

The package has no dependency and it's light.

  1. Install from pypi.org
pip install django-case-insensitive-field

  1. Create a fields.py file

  2. Add a Mixin to the Field you want to make case insensitive. Example below:

# fields.pyfrom django_case_insensitive_field import CaseInsensitiveFieldMixin
from django.db.models import CharField

classLowerCharField(CaseInsensitiveFieldMixin, CharField):
    """[summary]
    Makes django CharField case insensitive \n
    Extends both the `CaseInsensitiveFieldMixin` and  CharField \n
    Then you can import 
    """def__init__(self, *args, **kwargs):

        super(CaseInsensitiveFieldMixin, self).__init__(*args, **kwargs)
  1. Use the new field everywhere in your model/code
# models.pyfrom .fields import LowerCharField


classUserModel(models.Model):

    username = LowerCharField(max_length=16, unique=True)

user1 = UserModel(username='user1') # will go through


user2 = UserModel(username='User1') # will not go through

That's all!

Post a Comment for "How To Implement Django Case Insensitive Model Field?"