简体   繁体   中英

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM