Creating login and logout class based views in Django 1.8
13,526
Go through the documentation https://docs.djangoproject.com/en/1.8/topics/class-based-views/intro/#using-class-based-views
from django.views.generic import View
class LoginView(View):
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/form')
else:
return HttpResponse("Inactive user.")
else:
return HttpResponseRedirect(settings.LOGIN_URL)
return render(request, "index.html")
class LogoutView(View):
def get(self, request):
logout(request)
return HttpResponseRedirect(settings.LOGIN_URL)
Author by
python
Updated on July 04, 2022Comments
-
python almost 2 years
I am learning class based views in Django 1.8, and wondering if anyone could help me here. I have created a function based login and logout views as you can see below:
LOGIN
def Login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect('/form') else: return HttpResponse("Inactive user.") else: return HttpResponseRedirect(settings.LOGIN_URL) return render(request, "index.html")
LOGOUT
def Logout(request): logout(request) return HttpResponseRedirect(settings.LOGIN_URL)
Could anyone help me to convert these views into
Class Based Views
in Django? I am pretty new to this stuff, and couldn't understand properly how exactly they are working. Will appreciate any help!