I am trying to create a login and logout page, so whenever a user is logged in, it only sees the logout option.
For login and logout I am using custom Forms and models. The problem I am facing is whenver I authenticate the user in views.py and redirect to a differnt page I cannot authenticate the user in html it is always false. I used “user.is_authenticate”. I am not sure how the value is being passed to the html. If I used the standard django login and logout template, I may be able to do it easily. Kindly help.
Code:
views.py
def login(request):
if request.method =='POST':
print("I am here1")
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = LoginAuthBackened().authenticate(request=request, username=username, password=password)
if user:
messages.success(request, f'Login Successful.')
return redirect('app-workspace')
else:
messages.error(request, f'Password Incorrect !')
return redirect('app-login')
else:
print(form.errors)
else:
form = LoginForm()
return render(request, 'users/login.html', {'form': form})
html:
models.py
--------------
from django.db import models
# Create your models here.
# One Hospital can have multiple staffs. So many to one/one to many
class HospitalDataModel(models.Model):
hospital_name = models.CharField(max_length=50)
def __str__(self):
return f"Hospital Added: {self.hospital_name}"
class StaffDataModel(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
dept_name = models.CharField(max_length=50)
doctor_id = models.IntegerField()
username = models.CharField(max_length=15, null=True)
password = models.CharField(max_length=20, null=True)
# Since a single hospital can have multiple staff that is why one to many
hospital = models.ForeignKey(HospitalDataModel, on_delete=models.CASCADE)
def __str__(self):
return f"Doctor {self.first_name} {self.last_name}"
forms.py
from django import forms
from random import randrange as rand_num
from .models import HospitalDataModel, StaffDataModel
class UserCreationForm(forms.ModelForm):
first_name = forms.CharField(label='First Name', max_length=100)
last_name = forms.CharField(label='Last Name', max_length=100)
username = forms.CharField(label='Username', max_length=100)
dept_name = forms.CharField(label='Department', max_length=50, required=False)
doctor_id = forms.IntegerField(initial=str(rand_num(0,100)))
doctor_id.disabled = True
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = StaffDataModel
fields = [ 'doctor_id', 'first_name', 'last_name', 'username', 'password']
class HospitalForm(forms.ModelForm):
class Meta:
model = HospitalDataModel
fields = '__all__'
class LoginForm(forms.Form):
username = forms.CharField(label='Username', max_length=100)
password = forms.CharField(widget=forms.PasswordInput())
login_backend
from .models import StaffDataModel
class LoginAuthBackened():
def authenticate(self, request, username=None, password=None):
try:
print(username, password)
user = StaffDataModel.objects.get(username=username)
if user.password == password:
return user
else:
return False
except Exception as e:
print(e)
return None
def get_user(self, user_id):
try:
return StaffDataModel.objects.get(pk=user_id)
except:
return None