Django自定义用户模型EmailField未经验证

时间:2016-03-26 01:08:15

标签: python django validation python-3.x django-models

当我在Django中覆盖用户模型时,我不确定我正在做什么/期望出错或者在验证EmailField时存在问题。 基本上我想要的是删除用户名和制作电子邮件地址用户名(或唯一标识符),所以我确实覆盖了我的用户模型,

class CustomUser(AbstractBaseUser, PermissionsMixin):
    first_name = models.CharField(_('first name'), max_length=30, blank=True, null=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True, null=True)
    email = models.EmailField(_('email address'), null=False, blank=False, unique=True)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin site.'))
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    REQUIRED_FIELDS = ()
    USERNAME_FIELD = 'email'

    objects = CustomUserManager()

    # Plus all the remaining stuff / methods we need override 

现在问题是即使使用无效的电子邮件地址我也可以创建用户,似乎没有在字段级别上进行验证。

from django.contrib.auth import get_user_model
User = get_user_model()
User(email='iamnotemail', password='pass').save()
User.objects.get(email='ghjkl')
<CustomUser: ghjkl>

我还尝试添加field_clean,并在字段中添加自定义电子邮件验证工具,但没有运气。

如果您有任何想法/线索,请帮助我。

由于

注意:我使用的是Django 1.9

1 个答案:

答案 0 :(得分:0)

要验证模型字段,请不要直接保存实例。

在保存之前在模型上运行clean_fields()和/或full_clean()

>>> u = User(username='foo', password='bar', email='foobar')
>>> u
<User: foo>
>>> u.clean_fields()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/vikas/.virtualenvs/venv/lib/python3.4/site-packages/django/db/models/base.py", line 1161, in clean_fields
    raise ValidationError(errors)
django.core.exceptions.ValidationError: {'email': ['Enter a valid email address.']}
>>> u.full_clean()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/vikas/.virtualenvs/venv/lib/python3.4/site-packages/django/db/models/base.py", line 1136, in full_clean
    raise ValidationError(errors)
django.core.exceptions.ValidationError: {'email': ['Enter a valid email address.']}
>>> 

了解模型字段验证@ django-docs

此外,保存这样的用户实例是一个非常的坏主意。始终使用create_user()方法创建用户。