I want to check three fields before logging in. Username and password are default in authenticate function but I want to check whether user is live member or not. I have created field is_live in auth_user model. But when I put this third argument in authenticate function, it only check username and password field and ignore the third parameter of is_live.
I have used decorator of is_staff i.e., staff_member_required. Similarly I tried to reuse this decorator with is_live. But it didnt work. Now simply I want to check three parameters within authenticate function, username, password and is_live.
def login_user(request):
if request.method=="POST":
username=request.POST.get('phone')
password=request.POST.get('psw')
if not User.objects.filter(username=username).exists():
messages.error(request,'invalid username')
return redirect('/login_form/')
user=authenticate(username=username,password=password,is_staff=1)#three params
if user is None:
messages.error(request,"invalid password")
return redirect('/login_form/')
else:
login(request,user)
return redirect('/index')
#return HttpResponseRedirect(reverse("index"))
return HttpResponse("error")
I think you need to override the authenticate method as mentioned in the documentation here
from django.conf import settings
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User
class SettingsBackend(BaseBackend):
def authenticate(self, request, username=None, password=None, is_live=None):
login_valid = settings.ADMIN_LOGIN == username
pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
if login_valid and pwd_valid and is_live:
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
# Create a new user. There's no need to set a password
# because only the password from settings.py is checked.
user = User(username=username)
user.is_staff = True
user.is_superuser = True
user.save()
return user
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
The above example shows you how to customize the authenticate method for admin users but you can do the same for all other user types.
for more details, you can check the following question and the answers Django: How to override authenticate() method?