Home > other >  is there an efficient way of preventing the same email addresses registered with the different capit
is there an efficient way of preventing the same email addresses registered with the different capit

Time:12-11

In views.py

 if User.objects.filter(email = email).exists():
                messages.info(request, 'Email already in use')
                return redirect('signup')

Django only checks if the exact email with the exact capitalization exists so for example if there is [email protected] in the user object and I signup with [email protected] instead of telling it that email already in use it creates another user for the gmail with it's unique capitalization.

admin user panel

CodePudding user response:

You can use iexact for that.

Case-insensitive exact match. If the value provided for comparison is None, it will be interpreted as an SQL NULL.

Example from docs:

Blog.objects.get(name__iexact='beatles blog')
Blog.objects.get(name__iexact=None)

In your case:

if User.objects.filter(email__iexact=email).exists():
    ...

CodePudding user response:

Django BaseUserManager does normalize, but only the domain part. If you want to normalize the local part of the email address you need to normalize the data on object creation.

Its possible to do that by creating your own customUserManager as in this example, there you would normalize the local part and domain into a lower(), the model would be in charge of the validation with the unique=True param, something like:

class MyUserManager(BaseUserManager):
    def create_user(self, email, date_of_birth, password=None):
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=email.lower(),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = MyUserManager()
  • Related