tags:

views:

492

answers:

2

Hi, how can I specify a blacklist for a CharField. However I want the blacklist to be effective in the Django admin panel aswell...otherwise I would just validate it in the view.

By blacklist I mean values that can't be used. I also set unique for the value but I would like to disable a few strings aswell.

Thanks, Max

A: 

This is not possible out of the box. You would have to write a custom form field or otherwise add custom admin handling to do admin-level validation. To do it at the database level, I suspect you would need to set up some kind of trigger and stored procedure, but that's not my area so I'll leave that to others.

Cide
+1  A: 

I would override the model's save() method and the to be inserted value against a blacklist before calling the parent class' save() method.

Something like that (simplified):

class BlackListModel(models.Model):   
   blacklist = ['a', 'b', 'c']

   # your model fields definitions...

   def save(self, *args, **kwargs):
        if self.blacklist_field in self.blacklist:
            raise Exception("Attempting to save a blacklisted value!")
        return super(BlackListModel, self).save(*args, **kwargs)

That way it works in all of your applications.

Haes