I want to redirect to the main page if the user is already authenticated. So I want a redirect from / to /main
views.py:
class LoginView(FormView):
form_class = LoginForm
success_url = reverse_lazy('main')
template_name = 'module/login.html'
def form_valid(self, form):
if self.request.user.is_authenticated():
return redirect(settings.LOGIN_REDIRECT_URL)
else:
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(self.request, user)
return super(LoginView, self).form_valid(form)
else:
return self.form_invalid(form)
settings.py:
LOGIN_REDIRECT_URL = reverse_lazy('main')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')
I tried also to add a get function, but then it call itself only infinite times.
def get(self, request, *args, **kwargs):
if request.user.is_authenticated():
return HttpResponseRedirect('main')
else:
return HttpResponseRedirect('/login/')
urls.py:
url(r'^$', views.LoginView.as_view(), name='login'),
url(r'^login/', views.LoginView.as_view(), name='login'),
You do redirect to the view itself in the else part, hence the infinite redirect loop. Do instead:
def get(self, request, *args, **kwargs):
if request.user.is_authenticated():
return HttpResponseRedirect('main')
return super(LoginView, self).get(request, *args, **kwargs)
you should also rename the first of your two views in urls.py to 'main'.
If your app is Django 2.x or 3.x then this is the way.
from django.contrib.auth import views as auth_views
from django.urls import path
urlpatterns = [
path('login/', auth_views.LoginView.as_view(redirect_authenticated_user=True), name='login'),
]
I couldn't get any of these solutions to work for what I needed so I'll post my working solution here. In my view I used redirect and render, both imported from django.shortcuts.
class ManagementPageView(TemplateView):
# Make a dispatch method to handle authentication
def dispatch(self, *args, **kwargs):
# Check if user is authenticated
if not self.request.user.is_authenticated:
# Redirect them to the home page if not
return redirect('home')
# Render the template if they are
return render(self.request, 'management.html')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With