我为我的用户名字段添加了自定义验证
我的正则表达式是^[a-zA-Z0-9_]{1,15}$
,我需要验证长度为1-15的a-z,0-9和_(下划线)。
def validate_username(value):
valid_username = r'^[a-zA-Z0-9_]{1,15}$'
validator = RegexValidator(regex=valid_username, message='a-z0-9 [1-15].', code='Invalid Name')
validator(value)
return value
在save()
上验证,
def save(self, **kwargs):
if self.username:
self.username = validate_username(self.username)
super(AbstractBaseUser, self).save(**kwargs)
这完全适用于Django shell,
>>> from django.core.validators import RegexValidator
>>> valid_username = r'^[a-zA-Z0-9_]{1,15}$'
>>> validator = RegexValidator(regex=valid_username, message='alphanumerics and underscores are allowed [1-15].',
code='Invalid Name')
>>> validator('')
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/core/validators.py", line 61, in __call__
raise ValidationError(self.message, code=self.code)
ValidationError: [u'alphanumerics and underscores are allowed [1-15].']
但是当我尝试使用用户名为""
的shell创建用户时。
>>> x = User.objects.create(email="me@localhost.com", username="")
>>> x.username
''
>>> x = User.objects.create(email="me@localhosted.com", username="")
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/db/models/query.py", line 401, in create
obj.save(force_insert=True, using=self.db)
File "/home/marty/projects/cleo/applications/auth/users/models.py", line 85, in save
super(AbstractBaseUser, self).save(**kwargs)
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/db/models/base.py", line 708, in save
force_update=force_update, update_fields=update_fields)
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/db/models/base.py", line 736, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/db/models/base.py", line 820, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/db/models/base.py", line 859, in _do_insert
using=using, raw=raw)
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/db/models/query.py", line 1039, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1060, in execute_sql
cursor.execute(sql, params)
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/marty/.virtualenvs/jk/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: UNIQUE constraint failed: users_user.username
第一次允许我创建一个空字符串作为用户名的用户,第二次它会引发完整性错误。我希望系统在""
上引发完整性错误作为用户名。
我做错了什么?
答案 0 :(得分:2)
当字符串为空时,validator
方法永远不会调用save
:
if self.username: # an empty string will not pass this condition
self.username = validate_username(self.username)