当前位置:  开发笔记 > 编程语言 > 正文

在Django 1.8中创建基于登录和注销类的视图

如何解决《在Django1.8中创建基于登录和注销类的视图》经验,为你挑选了1个好方法。

我正在Django 1.8中学习基于类的视图,并想知道是否有人可以在这里帮助我.我已经创建了一个基于函数的登录和注销视图,如下所示:

登录

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")

登出

def Logout(request):
    logout(request)
    return HttpResponseRedirect(settings.LOGIN_URL)

有人可以帮我把这些视图转换成Class Based ViewsDjango吗?我对这些东西很陌生,并且无法正确理解它们究竟是如何工作的.将不胜感激任何帮助!



1> Geo Jacob..:

浏览文档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)

推荐阅读
吻过彩虹的脸_378
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有