我有一个登录视图,如下所示:
class LoginView(TemplateView):
template_name = 'login.html'
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user:
login(request, user)
return redirect(reverse('index'))
else:
messages.add_message(request, messages.ERROR, 'Login failed')
return render(request, self.template_name, {'username' : username})
现在,我想修改它,以便如果用户已经登录并访问此网址,则不会呈现模板并将其重新发送到索引页面(或登录页面之外的任何其他页面)。我试过覆盖get方法,但它没有用。那么什么是正确的解决方案?
答案 0 :(得分:1)
def post(self, request):
if request.user.is_authenticated():
return HttpResponseRedirect("/yourIndex/")
else:
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user:
login(request, user)
return redirect(reverse('index'))
else:
messages.add_message(request, messages.ERROR, 'Login failed')
return render(request, self.template_name, {'username' : username})