Ammar rady
Ammar rady

Reputation: 146

custom user model making the emails unique but not case sensetive?

so I have a custom user model to make the users sign up/in using emails instead of a username the problem is I grab the email as it's entered in the form and save and my model is assigning this field to be unique so it's case sensitive.

so you see the problem if a user entered the email uppercase he can't log in till he enters the email similar to that of the signup page.

my model

class MyUser(AbstractUser):
    username =         None
    email =            models.EmailField(unique=True)   

the form

class SignupForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model =     MyUser
        fields =    ('email', 'password1', 'password2')

and this is the view to send confirmation emails to the users

def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            mail_subject = 'Activate your Sentizer account.'
            message = render_to_string('acc_active_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(),
                'token':account_activation_token.make_token(user),
            })
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(
                        subject=mail_subject, body=message, to=[to_email], reply_to=[to_email],headers={'Content-Type': 'text/plain'},
            )
            email.send(fail_silently=False)
            messages.info(request,"Please confirm your email to be able to login")
            return HttpResponseRedirect(reverse_lazy('accounts:login'))
    else:
        form = SignupForm()
    return render(request, 'accounts/signup.html', {'form': form})

and thanks for ur help.

Upvotes: 0

Views: 79

Answers (1)

Chris
Chris

Reputation: 2212

If converting the email address to lowercase is convenient for you, you could just do that. So in your view:

if form.is_valid():
    user = form.save(commit=False)
    user.is_active = False
    user.email = form.cleaned_data['email'].lower()
    user.save()
    # ...

If you do that you have to make sure that on logging in the email address entered by the user in your signup form is converted to lowercase to, of course.

Upvotes: 1

Related Questions