猿问

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

所以我有一个面向客户的电子商务应用程序,带有 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 中编写的验证来避免重复自己。


这是我的代码,感谢您的帮助!


模型.py

class 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


守候你守候我
浏览 180回答 2
2回答

慕工程0101907

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

qq_遁去的一_1

需要注意的一件事是CharField 没有 min_length 属性。因此,作为一种不明智的替代方案,您可以使用 Min/MaxValueValidator Min/MaxValueValidator,而不是使用 Min/MaxLengthValidator。很酷的是,您可以将验证器子类化来处理自定义错误消息:模型.pyfrom django.core.validators import MinValueValidator, MaxValueValidatorclass ZipcodeMaxValueValidator(MaxValueValidator):&nbsp; &nbsp; message = ("AWWW YEA ERROR!!")class User(models.Model):&nbsp; &nbsp; zipcode = models.IntegerField(validators=[MinValueValidator(99999), ZipcodeMaxValueValidator(99999)]
随时随地看视频慕课网APP

相关分类

Python
我要回答