Implementing case-insensitive username and email with class base view in Django 3

Viewed 122

I'm trying to implement a registration mechanism that should have case insensitive query on username and email with class base view in a Django project. I tried many methods but none of them worked. Anybody Has A Solution??

views.py:

class RegisterView(FormView):
    template_name = 'users/user_register.html'
    form_class = UserRegistrationForm
    redirect_authenticated_user = True
    success_url = reverse_lazy('index')

    def form_valid(self, form):
        user = form.save()
        if user is not None:
            login(self.request, user)
        return super(RegisterView, self).form_valid(form)
    
    def get(self, *args, **kwargs):
        if self.request.user.is_authenticated:
            return redirect('index')
        return super(RegisterView, self).get(*args, **kwargs)

forms.py:

class UserRegistrationForm(UserCreationForm):
    email = forms.EmailField()
    
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']  
2 Answers
# For username, you have to create your own usermanager class and point it in your user model class. For email id, django uses the normalize_email function in BaseUserManager which always change the email ids in lowercase. You can customize that function in BaseUserManager, If you want.

from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager

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

class User(AbstractBaseUser):
    objects = UserManager()
    # other changes

You can use the clean_<field_name> method inside your form.

class UserRegistrationForm(UserCreationForm):
    email = forms.EmailField()
    
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']  

    def clean_username(self):
         username = self.cleaned_data.get('username')
         If User.objects.filter(username__iexact=username).exists():
             raise forms.ValidationError('Username Already  Exists')
         return username

Related