How to login with email instead of username in Django?

Submitted 3 years, 6 months ago
Ticket #268
Views 230
Language/Framework Django
Priority Low
Status Closed

How to login with email instead of username in Django?

Submitted on Oct 27, 20
add a comment

1 Answer

Verified

Use below method to login with email or username.

from django.conf import settings
from django.contrib.auth import authenticate, login, REDIRECT_FIELD_NAME
from django.shortcuts import render_to_response
from django.contrib.sites.models import Site
from django.template import Context, RequestContext
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
@csrf_protect
@never_cache
def signin(request,redirect_field_name=REDIRECT_FIELD_NAME,authentication_form=LoginForm):
redirect_to = request.REQUEST.get(redirect_field_name, settings.LOGIN_REDIRECT_URL)
form = authentication_form()
current_site = Site.objects.get_current()
if request.method == “POST”:
pDict =request.POST.copy()
form = authentication_form(data=request.POST)
if form.is_valid():
username = form.cleaned_data[‘username’]
password = form.cleaned_data[‘password’]
try:
user = User.objects.get(email=username)
username = user.username
except User.DoesNotExist:
username = username
user = authenticate(username=username, password=password)
# Log the user in.
login(request, user)
return HttpResponseRedirect(redirect_to)
else:
form = authentication_form()
request.session.set_test_cookie()
if Site._meta.installed:
current_site = Site.objects.get_current()
else:
current_site = RequestSite(request)
return render_to_response(‘login.html’,locals(), context_instance=RequestContext(request))

method to login with email or username.

Submitted 3 years, 5 months ago


Latest Blogs