I am trying to create an auth backend to allow my users to log in using either their email address or their username in Django 1.6 with a custom user model. The backend work
Those who are still struggling. Because of following multiple tutorials, we end up with this kind of a mess. Actually there are multiple ways to create login view in Django. I was kinda mixing these solutions in my Django predefined method of log in using
def login_request(request):
form = AuthenticationForm()
return render(request = request,
template_name = "main/login.html",
context={"form":form})
But now I have worked around this problem by using this simple approach without modifying the authentication backend.
In root directory (mysite) urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
]
In your app directory urls.py
urlpatterns = [
path('accounts/login/', views.login_view, name='login'),
]
In views.py
def login_view(request):
if request.method == 'POST':
userinput = request.POST['username']
try:
username = User.objects.get(email=userinput).username
except User.DoesNotExist:
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
messages.success(request,"Login successfull")
return redirect('home')
else:
messages.error(request,'Invalid credentials, Please check username/email or password. ')
return render(request, "registration/login.html")
Finally, In templates (registration/login.html)
SIGN IN
This is the easiest solution I came up with.