mistero
mistero

Reputation: 5309

Django CharField limitations

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

Upvotes: 1

Views: 1190

Answers (3)

T. Christiansen
T. Christiansen

Reputation: 1038

Since we're a few years later, you should write a custom blacklist validator:

from django.db import models    
from django.core.exceptions import ValidationError

def validate_blacklist(value):
    if value in ['a', 'b', 'c']:
        raise ValidationError(
            "'a', 'b' and 'c' are prohibited!",
            params={'value': value},
        )

class MyModel(models.Model):
    even_field = models.CharField(max_length=200, validators=[validate_even])

See: Django Validators for full documentation.

Upvotes: 4

Haes
Haes

Reputation: 13116

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.

Upvotes: 2

André Eriksson
André Eriksson

Reputation: 4360

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.

Upvotes: 0

Related Questions