django authenticate code example
Example 1: django authenticate
from django.contrib.auth import authenticate
Example 2: from django.contrib.auth.decorators import authenticate, login
from django.contrib.auth import authenticate, login
Example 3: user login validation django
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
...
else:
...
Example 4: django authenticate with email
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class EmailBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
UserModel = get_user_model()
try:
user = UserModel.objects.get(email=username)
except UserModel.DoesNotExist:
return None
else:
if user.check_password(password):
return user
return None