Reputation: 155
I am trying the build in method authenticate() to login employees but that does not seem to work. I have not used the default model User provided by django instead I have used my own model Employee here.
Here is what I have in my views.py
def login(request):
if request.method == 'POST':
password = request.POST['password']
emailid = request.POST['email']
employee = auth.authenticate(username=emailid,password=password)
if employee is not None:
auth.login(request,employee)
return render(request,'register/html')
else:
messages.error(request,'Email id dosent exist')
return redirect('login')
else:
return render(request,'employee/login.html')
while my custom code does the authentication
def login(request):
if request.method == 'POST':
password = request.POST['password']
emailid = request.POST['username']
if Employee.objects.filter(firstname=emailid).exists():
if Employee.objects.filter(password=password):
messages.success(request,'Loged Out')
return redirect('vacant-rooms')
else:
messages.error(request,'Wrong emailid')
return redirect('login')
else:
messages.error(request,'wrong password')
return redirect('login')
else:
return render(request,'employee/login.html')
Here is my model
class Employee(models.Model):
firstname = models.CharField(max_length=15)
lastname = models.CharField(max_length=15)
age = models.IntegerField()
sex = models.CharField(max_length=10)
phoneno = models.IntegerField()
emailid = models.CharField(max_length=25)
address = models.CharField(max_length=50)
salary = models.IntegerField()
designation = models.CharField(max_length=10)
password = models.CharField(max_length=10)
aadharno = models.CharField(max_length=15)
datejoined = models.DateField(default=timezone)
Its a dumb question maybe but is the buit in authentication not working because I do not have a username field in my model?
Upvotes: 0
Views: 1011
Reputation: 581
I think you shouldn't do that. Django already has a User infrastructure and to use functions like authenticate, you need to inherit one of the AbstractUser or AbstractBaseUser classes. If you just define models like that, you have to do a lot of the work that Django has already done, and I definitely don't recommend it. I leave some helpful documentation and articles below. If you need any help, write a comment and I can help as best I can.
Official Django Doc Customizing authentication
Upvotes: 1