区分大小写django

qmelpv7a  于 2023-01-27  发布在  Go
关注(0)|答案(1)|浏览(262)

登录时我试过放这个代码去激活字符敏感,但是没有用,是什么问题?还是出现了,请考虑字符敏感
我想用这个方法,我不想用后端方法请帮我查找问题

class CustomUserManager(UserManager):
    def get_by_natural_key(self, username):
        return self.get(username__iexact=username)

class User(AbstractBaseUser):
    """
    Decapolis main User model
    """
    username = models.CharField(max_length=40, unique=True)
    email = models.CharField(max_length=40, unique=True)

    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)

    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)

    company = models.ForeignKey(settings.COMPANY_MODEL, on_delete=models.CASCADE, related_name='user_company',
                                null=True, blank=True)
    roles = models.ManyToManyField(Role, blank=True)

    objects = CustomUserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']
     def has_role(self, role_name):
        """
        Check user has role

        :param role_name: role name to check
        :type role_name: str
        :return: True or False
        :rtype: bool

        """
        return True if role_name in self.roles else False

    def has_perm(self, perm, obj=None):
        """
        Does the user have a specific permission?

        Not implemented yet

        :param perm: permission to check
        :type perm: str
        :param obj: object to check
        :type obj:
        :return:
        :rtype:

        """
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        """
        Does the user have permissions to view the app `app_label`?

        Not implemented yet

        :param app_label:
        :type app_label:
        :return:
        :rtype:
        """

        # Simplest possible answer: Yes, always
        return True

    def get_full_name(self):
        """
        Returns the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def __str__(self):
        return self.username
7cwmlq89

7cwmlq891#

Use validator like this
    def validate_caseinsensitive(value):
        if User.objects.filter(code__iexact=value).exists():
            raise ValidationError('This User already exists.')
        return value

在www.example.com中的数量models.py

class User(BaseUser):
    code = models.CharField(max_length=10, unique=True, validators=[validate_caseinsensitive])
    # ... other code ...
    def save(self, *args, **kwargs):
        self.code = self.code.upper()
        super(User, self).save(*args, **kwargs)
    # ... other code ...

相关问题