【问题标题】:Django Custom User Model EmailField not ValidatedDjango 自定义用户模型 EmailField 未验证
【发布时间】:2016-03-26 01:08:14
【问题描述】:

当您在 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

【问题讨论】:

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


    【解决方案1】:

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

    保存前在模型上运行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() 方法创建用户。

    【讨论】:

      猜你喜欢
      • 2015-03-08
      • 1970-01-01
      • 2016-02-11
      • 2012-05-05
      • 2013-12-13
      • 1970-01-01
      • 2021-01-09
      • 2011-11-14
      • 1970-01-01
      相关资源
      最近更新 更多