If you want to do a custom authentication I would suggest making a form for that. Make a form that takes email and password and then write the clean method to validate the two.
Customize user authentication
-
02-10-2022 - |
Question
Can anyone give more informations about customizing the Django authentication system. Well, I created a custom user in which I use the email as an identifier:
USERNAME_FIELD = 'email'
and I created a custom authentication backend, and I changed authentication backend to this new one in the settings file :
class Custom_Authentication(ModelBackend):
def authenticate(self, email=None, password=None):
try:
user = self.user_class.objects.get(email=email)
if user.check_password(password):
return user
except self.user_class.DoesNotExist:
return None
def get_user(self, user_id):
try:
return self.user_class.objects.get(pk=user_id)
except self.user_class.DoesNotExist:
return None
@property
def user_class(self):
if not hasattr(self, '_user_class'):
self._user_class = get_model(*settings.AUTH_USER_MODEL.split('.', 2))
if not self._user_class:
raise ImproperlyConfigured('Could not get custom user model')
return self._user_class
but now i don't know how to authenticate a custom user using his email, do I use :
from django.contrib import auth
def auth_view(request):
email = request.POST.get('email', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=email, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/loggedin/')
else:
return HttpResponseRedirect('/invalid/')
I tried this and it seems that it doesn't recognize the user I created using the admin interface. Are there any other things that I have to change?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow