为了账号安全,请及时绑定邮箱和手机立即绑定

将 Django 验证器与管理员一起使用 - TypeError:

将 Django 验证器与管理员一起使用 - TypeError:

守候你守候我 2021-06-16 14:12:31
所以我有一个面向客户的电子商务应用程序,带有 Django 管理界面。我希望将使用管理员的员工能够创建用户。问题是我内置的自定义正则表达式验证仅适用于面向客户的一侧,当员工想要使用管理员创建新用户时,我在尝试创建用户时使用 Django 验证器会引发错误。我想知道(1)是否有一种方法可以重用我的 UserManager 类(继承自models.Manager)来处理客户端验证,Django admin 也是如此。如果没有,那么 (2) 如果我要依赖 Django 验证器,我该如何清理代码以免抛出以下错误:TypeError: "object of type 'int' has no len()我做了一些功课试图解决这个问题,发现这个线程:TypeError: object of type 'int' has no len() error需要帮助这基本上解释了此示例抛出的错误是因为它试图在 int 而不是列表上调用 len() 。我不明白的是,当用户自己注册时,为什么我不会在面向客户的方面遇到同样的错误?无论如何,鉴于我如何设置我的 UserManager,我无法弄清楚如何实施该解决方案。我没有使用 Django Forms 并尝试使用一些干净的方法,但我也试图通过重用我已经在 UserManager 中编写的验证来避免重复自己。这是我的代码,感谢您的帮助!模型.pyclass UserManager(models.Manager):    def validation(self, postData, error_validation):    errors = {}    if error_validation == 'register':        if not NAME_REGEX.match(postData['first_name']):            errors['first_name'] = "First name can only contain letters."        if not NAME_REGEX.match(postData['last_name']):            errors['last_name'] = "Last name can only contain letters."        elif User.objects.filter(email=postData['email']):            errors['email'] = "Email already being used."        elif len(postData['password']) < 8:            errors['password'] = "Password must contain 8 or more characters."        elif not postData['password'] == postData['confirm_password']:            errors['password'] = "Both passwords must match!"    if error_validation == 'login':        user = User.objects.filter(email=postData['email'])        if not user or not bcrypt.checkpw(postData['password'].encode(), user[0].password.encode()):            errors['user_login'] = "Invalid credentials."    return errors
查看完整描述

2 回答

?
慕工程0101907

TA贡献1887条经验 获得超5个赞

您正在IntegerFields 上使用MinLengthValidatorMaxLengthValidator,它将尝试对整数应用 len() 函数。这就是为什么你会遇到这种错误。您可以将您的zipcodephone属性更改为 CharField,或者只是删除验证器。


查看完整回答
反对 回复 2021-06-22
?
qq_遁去的一_1

TA贡献1725条经验 获得超8个赞

需要注意的一件事是CharField 没有 min_length 属性。


因此,作为一种不明智的替代方案,您可以使用 Min/MaxValueValidator Min/MaxValueValidator,而不是使用 Min/MaxLengthValidator。很酷的是,您可以将验证器子类化来处理自定义错误消息:


模型.py


from django.core.validators import MinValueValidator, MaxValueValidator



class ZipcodeMaxValueValidator(MaxValueValidator):

    message = ("AWWW YEA ERROR!!")


class User(models.Model):

    zipcode = models.IntegerField(validators=[MinValueValidator(99999), ZipcodeMaxValueValidator(99999)]



查看完整回答
反对 回复 2021-06-22
  • 2 回答
  • 0 关注
  • 178 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号