我正在使用Django 1.10.6并且正在处理用户注册表单。在我的forms.py
验证过程中,我试图从clean方法中调用UserAttributeSimilarityValidator
,但是我在查找它需要的用户对象参数时遇到了一些麻烦。请求数据是一个QueryDict,而不是一个对象,所以我对我应该使用的对象感到困惑。
以下是我提供的链接中的UserAttributeSimilarityValidator
课程
class UserAttributeSimilarityValidator(object):
DEFAULT_USER_ATTRIBUTES = ('username', 'first_name', 'last_name', 'email')
def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7):
self.user_attributes = user_attributes
self.max_similarity = max_similarity
def validate(self, password, user=None):
if not user:
return
for attribute_name in self.user_attributes:
value = getattr(user, attribute_name, None)
if not value or not isinstance(value, string_types):
continue
value_parts = re.split('\W+', value) + [value]
for value_part in value_parts:
if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() > self.max_similarity:
verbose_name = force_text(user._meta.get_field(attribute_name).verbose_name)
raise ValidationError(
_("The password is too similar to the %(verbose_name)s."),
code='password_too_similar',
params={'verbose_name': verbose_name},
)
def get_help_text(self):
return _("Your password can't be too similar to your other personal information.")
这是forms.py
def clean(self):
cleaned_data = super(RegisterForm, self).clean()
password = cleaned_data.get('password')
password_validation.UserAttributeSimilarityValidator().validate(password, USER_OBJET_HERE)
我尝试使用namedtuple
来创建用户对象
user = namedtuple('user', 'username email')
user_attributes = user(username = self.data.get('username'), email = self.data.get('email'))
password_validation.UserAttributeSimilarityValidator().validate(password1, user_attributes)
当我这样做时,它失败并出现以下错误'user' object has no attribute '_meta'
。是否有我应该访问的表单创建的实际用户对象,或者我应该像我尝试的那样创建它?
更新我过度思考这个并让它发挥作用。我必须像这样手动设置User对象的用户名和电子邮件属性
from django.contrib.auth.models import User
...
User.username = self.data.get('username')
User.email = self.data.get('email')