Handling unique constraint for custom field in django admin
Hi I'm new to django and just took my first foray into using a custom field for my model. I have a Char field that I always want to keep in lowercase, so I implemented it as a custom field as follows (learned from another post on Stack Overflow):
from django.db import models
from django.db.models.fields import CharField
class LowercaseCharField(CharField):
def pre_save(self, model_instance, add):
current_value = getattr(model_instance, self.attname)
setattr(model_instance, self.attname, current_value.lower())
return getattr(model_instance, self.attname)
class Item(models.Model):
name = LowercaseCharField(max_length=50, unique=True)
def __str__(self):
return self.name
I checked this in admin, and indeed, the field record is correctly converted to lowercase before saving. Unfortunately, when I tested the uniqueness constraint, the admin did not handle the integrity of the error gracefully. Instead of getting a clean error as I do if this is an exact match with the result:
I am getting an ugly error page:
How do I configure a custom field so that the unique constraint is "early" enough to trigger a graceful error or otherwise change the admin so that this "later" error is handled more gracefully?
(Note: I am just using sqlite3 for my db at the moment)
UPDATE: In case anyone is interested, here's the modified code that worked for me:
class LowercaseCharField(CharField):
def get_db_prep_value(self, value, connection, prepared=False):
return value.lower()
source to share