简体   繁体   English

Django CharField限制

[英]Django CharField limitations

how can I specify a blacklist for a CharField. 如何为CharField指定黑名单。 However I want the blacklist to be effective in the Django admin panel aswell...otherwise I would just validate it in the view. 但是我也希望黑名单在Django管理面板中也能有效...否则,我只会在视图中对其进行验证。

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. 在调用父类的save()方法之前,我将覆盖模型的save()方法和要插入黑名单的值。

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. 有关完整的文档,请参见: Django Validators

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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