How to save email as lower case in django while signing up user?

Question:

I want to turn emails to lower case while signing up a new user, i have tried doing it using the lower() method, but it does not automatically sign in the user using the login() function. Maybe i am not doing it the right way?

Now what would be the right way to achieve this?

NOTE: I would post the full Code

def registerRef(request, *args, **kwargs):
    if request.user.is_authenticated:
        return redirect('core:index')

    profile_id = request.session.get('ref_profile')
    print('profile_id', profile_id)
    try:
        signup_point = SignUpPoint.objects.get()
    except:
        signup_point = None 

    code = str(kwargs.get('ref_code'))
    try:
        profile = Profile.objects.get(code=code)
        profile_user = Profile.objects.get(code=code)
        request.session['ref_profile'] = profile.id
        print('Referer Profile:', profile.id)
    except:
        pass
    print("Session Expiry Date:" + str(request.session.get_expiry_age()))

    form = UserRegisterForm(request.POST or None)
    if form.is_valid():
        if profile_id is not None:
            recommended_by_profile = Profile.objects.get(id=profile_id)
            ref_earn = InvestmentPackageID.objects.get()

            instance = form.save(commit=False)
            instance.email = instance.email.lower()
            instance.username = instance.username.lower()
            instance.save
            registered_user = User.objects.get(id=instance.id)
            registered_profile = Profile.objects.get(user=registered_user)
            registered_profile.recommended_by = recommended_by_profile.user
            
            my_recomended = Profile.objects.filter(recommended_by=profile_user.user).values_list('user__id', flat=True)
            print(my_recomended)
            # second_level_recommended=Profile.objects.filter(recommended_by__in=my_recomended)

            
            registered_profile.save()
            profile = Profile.objects.get(user=registered_user)
            profile.earning_point = signup_point.signup_point
            profile.main_all_earning += signup_point.signup_point
            profile.save()

            if recommended_by_profile.level_1 == True and recommended_by_profile.level_6 == False and recommended_by_profile.level_5 == False and recommended_by_profile.level_4 == False and recommended_by_profile.level_3 == False and recommended_by_profile.level_2 == False:
                recommended_by_profile.referral_point = recommended_by_profile.referral_point + ref_earn.ref_earn1
                recommended_by_profile.main_all_earning = recommended_by_profile.main_all_earning + ref_earn.ref_earn1
                recommended_by_profile.save()
                        
            else:
                recommended_by_profile.referral_point = recommended_by_profile.referral_point + 500
                recommended_by_profile.main_all_earning = recommended_by_profile.main_all_earning + 500
                recommended_by_profile.save()
                ActiveRefEarning.objects.create(user=registered_user, active_ref_earning_owner=recommended_by_profile.user, active_ref_earning=500)             
            
            profile.save()
            recommended_by_profile.save()
        
        else:
            instance = form.save()
            registered_user = User.objects.get(id=instance.id)
            profile = Profile.objects.get(user=registered_user)
            profile.earning_point = signup_point.signup_point
            profile.main_all_earning += signup_point.signup_point
            profile.save()

        username = form.cleaned_data.get('email')
        password = form.cleaned_data.get('password1')
        user = authenticate(username=username, password=password)
        login(request, user)
        NewsLetter.objects.create(email=username)
        messages.success(request, f"Hi {request.user.username}, {signup_point.signup_message}")

        return redirect('core:index')
    context = {'form':form}
    return render(request, 'userauths/sign-up.html', context)

Asked By: Destiny Franks

||

Answers:

Have you tried

user = authenticate(username=username.lower(), password=password)
login(request, user)

You need to lowercase it here so that auth system can find the already lowercased email you saved during registration.

Otherwise, try using casefold() instead of lower() on the email during login and registering

But give the first solution a try first.

Find more info about casefold() method here https://www.w3schools.com/python/ref_string_casefold.asp

Answered By: AbdulelahAGR

It is worth mentioning that, while most email providers make addresses case-insensitive, that is not guaranteed to be the case. So if you lowercase the email, there’s a small chance you won’t be able to actually send emails to the user (or worse, send it to an unintended recipient).

If you do want to proceed with this, you probably want to tackle this at the data layer (model level), but you can also do this in form validation as well. I’ll cover both approaches:

Using your database model

There are a few ways to implement this in your model. One way is to implement a custom field that implements get_prep_value. get_prep_value takes Python objects and prepares them for use in a DB query. So for all cases (querying, inserting, deleting, etc.) your lowercase logic will be applied.

class LowercaseCharField(models.CharField):
    def get_prep_value(self, value):
        return str(value).lower()

You could also implement a custom save method, but this may miss several cases where save is not called, like when using .update.

The advantage of this approach is that you only have to define this logic once and it should work anywhere your model (field) is being used.

Using form validation

You can implement the clean or clean_<fieldname> method in your UserRegisterForm to change the value to lowercase. In general, overriding the form methods is the best way to implement form validation and cleaning (not in your view logic).

class UserRegisterForm(ModelForm):
    ...
    def clean_email(self):
        email = self.cleaned_data['email']
        return email.lower()

However, this approach is not as good because you likely need this .lower() logic to be present in many other places: when making queries, deleting logic, views using different forms (like your login view!), etc.

Answered By: sytech
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.