Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating login and logout class based views in Django 1.8

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!

like image 598
python Avatar asked Dec 02 '15 04:12

python


People also ask

How does logout work in Django?

To log out a user who has been logged in via django.contrib.auth.login() , use django.contrib.auth.logout() within your view. It takes an HttpRequest object and has no return value. Example: from django.contrib.auth import logout def logout_view(request): logout(request) # Redirect to a success page.

How do I login as user in Django?

Django by default will look within a templates folder called registration for auth templates. The login template is called login. html . Create a new directory called templates and within it another directory called registration .


1 Answers

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)
like image 103
Geo Jacob Avatar answered Sep 22 '22 23:09

Geo Jacob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!