开发者

Django User model validators

开发者 https://www.devze.com 2023-02-16 21:17 出处:网络
Can anyone suggest a clever way to add validators to the Django User model?I create files and directories based on first_name, last_name, and username, so I开发者_开发问答\'d like to carefully control

Can anyone suggest a clever way to add validators to the Django User model? I create files and directories based on first_name, last_name, and username, so I开发者_开发问答'd like to carefully control what characters are allowed in there using the same standard validators I have on other models. I can't see an easy way to do this.

TIA

Ian


Really you should be subclassing the User object and adding validators the correct way, but if you like to live dangerously you could try monkey patching the User class as well.

You might put this in your app's __init__.py file...

from django.contrib.auth.models import User

def validate_for_fs(value): # <-- If the value string doesn't meet a condition required to be a name on the filesystem then throw a ValidationError
    if foo_condition_not_met:
        raise ValidationError(u'foo is not true for %s' % value)
    if bar_condition_not_met:
        raise ValidationError(u'bar is not true for %s' % value)

for field in [f for f in User._meta.fields if f.name in ['first_name','last_name','email']]:
    field.validators.append(validate_for_fs)
0

精彩评论

暂无评论...
验证码 换一张
取 消