I'm still new to Django. I have an admin user and a regular user who is not an admin. When admin login he should be redirected to '/admin_section' & when a regular user login he should be redirected to the '/' front page. Beyond that, it should be possible for an admin to be able to navigate to the '/' front page and see the page as a regular user can see.
I've been trying to search for an answer for this and the only thing I find is that I can use request.user.is_superuser in a view and ask whether the user is a superuser/admin or not. But the problem then becomes that admin will not have the ability to navigate to the front page ever. I have also set the login_redirect_url to "LOGIN_REDIRECT_URL = '/'" which means everytime a user login they will be redirected to the frontpage - but it should not be like that.
Here is my code so far (from the views.py file):
def home(request):
# if the user is not logged-in, show the loginpage
if not request.user.is_authenticated:
return HttpResponseRedirect('login')
# if the user is logged-in, show the frontpage
return render(request, 'mainapp/index.html')
# return the view for the admin section
def admin(request):
# if the user is logged-in & is an admin - show the admin section
if request.user.is_authenticated and request.user.is_superuser:
return render(request, 'mainapp/admin.html')
return redirect('home') # redirects to the home view
forms.py:
from django.contrib.auth.forms import AuthenticationForm
from django import forms
from django.contrib.auth import logout
from django.contrib.auth.mixins import LoginRequiredMixin, AccessMixin
# a class which act as a view - it displays the login-form
class LoginForm(AuthenticationForm, AccessMixin):
username=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
password=forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}))
urls.py:
path('login/', views_auth.LoginView.as_view(form_class=LoginForm, redirect_authenticated_user=True), name='login'), # login-page