I'm want my code to redirect students and teachers to two different pages when the login button is clicked but i kept getting this error: 'AnonymousUser' object has no attribute 'is_teacher'
Here is my login view code:
def login_user(request):
if request.method=='POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if request.user.is_teacher:
login(request,user)
return redirect('/myapp/home')
else:
login(request, user)
return redirect('/myapp/application')
else:
messages.error(request,"Invalid username or password")
else:
messages.error(request,"Invalid username or password")
return render(request, 'login.html',context={'form':AuthenticationForm()})
You should check user.is_teacher
, since that is the user you are authenticating. request.user
is at that moment the AnonymousUser
:
if user is not None:
if user.is_teacher: # 🖘 not request.user.is_teacher
login(request, user)
return redirect('/myapp/home')
You can also simplify your view to:
def login_user(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
user = form.get_user()
if user is not None:
login(request, user)
if user.is_teacher:
return redirect('/myapp/home')
else:
return redirect('/myapp/application')
else:
messages.error(request, 'Invalid username or password')
else:
messages.error(request, 'Invalid username or password')
form = AuthenticationForm()
Normally a redirect(…)
call [Django-doc] also takes the name of the view, not a path or URL.