Login with Email address

(Lance Haig) #1

Hey Everybody,

I would like to make it so that the people who use my App login with their email address as the username.
I have searched using google and found a few tutorials where you need to customise the AUTH mechanism and as someone new I was wondering what would be the best way forward for this.

I am still learning Django/Python/Coding so rely heavily on the Tutorials @vitor creates and has created.

My application will in the future have multi-tenancy and also the need for a custom signup form so that the first user can create the tenant.

I would appreciate some advice from you all.



(RicS) #2

new_user.email = form.cleaned_data[‘username’]

then, the username will be the @


(Lance Haig) #3

Where would this be added?
Would this be on the signup form?

This is my current signup form.

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class SignUpForm(UserCreationForm):
email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput())
class Meta:
model = User
fields = (‘username’, ‘email’, ‘password1’, ‘password2’)

(RicS) #4

Well, i’m really not sure that is the best way !
but it works for me.

def signup(request):
    template_name = 'registration/signup.html'

    if request.method == 'POST':
        form =  SignUpForm(request.POST)

        if form.is_valid():
            # Create a new user object but avoid saving it yet
            new_user = form.save(commit=False)
            # Make other things here

            # Save the User object
            new_user.email = form.cleaned_data['username']
            new_user.is_active = False

            return redirect('NameOfYourApp:signup_thanks')
            messages.warning(request, 'Oops, Something went wrong...')

        form = SignUpForm()

    return render(request, template_name, { 'form': form } )

def signup_thanks(request):
    template_name = 'registration/signup_thanks.html'
    return render(request, template_name)

Hope it helps !

1 Like
(RicS) #5

and the class form, in case…

class SignUpForm(UserCreationForm):  
     username = forms.CharField(label="email adress", max_length=254, required=True, widget=forms.EmailInput())
     class Meta:
         model = User
         fields = {'username', 'password1', 'password2'}
(Lance Haig) #6

Thanks for the pointers.

I will investigate it a bit.


(Augustus Ezenwankwo ) #7


(Lance Haig) #8

Thanks for this suggestion, I am still very new to Django and Python in general so it will take some time for me ti understand what needs to be done.

(Lance Haig) #9

This looks very promising thank you.
I have tried to implement it but it failed for me.

I will try again in a few days when I have time free again.

(RicS) #10

ok, what’s the error ? message ?
Try without the email confirmation paragraph.
I updated a bit the preliminary lines.
good luck,

(Basil Jose) #11

In order to use email as username in Django,
Just extend the AbstractBaseUser and then specify as USERNAME_FIELD = 'email’

then you can use the default login mechanism like below,

class LoginView(TemplateView):
    template_name = "login.html"
    form_class = AuthenticationForm

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return HttpResponseRedirect(reverse('home'))
        form = self.form_class(None, request.POST or None)
        return render(request, self.template_name, {'form': form})

    def post(self, request, *args, **kwargs):
        form = self.form_class(data=request.POST)
        next_url = request.POST.get('next', reverse('home'))
        if not next_url:
            next_url = reverse('home')
        if form.is_valid():
            auth_login(self.request, form.get_user())
            return HttpResponseRedirect(next_url)
        return render(request, self.template_name, {'form': form})

Refer How to Extend Django User Model by @vitor

(Cory Zue) #12

If you’re not against third party dependencies I’d recommend using django allauth for this. Once you’ve set it up it’s a simple setting to use email instead of username as the login.

(Lance Haig) #13

I am not against using allauth.
I have a requirement for using multi tenancy in the app and I don’t want to be stuck with having to add code for each new customer.

I will investigate this tomorrow as I was struggling with custom user auth anyway.

Thanks for the tip.