注销/登录视图问题

时间:2019-02-26 17:03:27

标签: python django

编辑:看来注销/ loginRequiredMixin功能在我的'/ admin'页面中有效,所以我认为问题出在我index.html中的按钮上

我无法在django应用程序中注销我的帐户。或者,如果可以,我可以进入需要登录的视图。

换句话说,我能够正确登录,但是当我尝试添加注销功能时,它似乎无能为力,或者LoginRequiredMixin无法正常工作

views.py

class LoginView(TemplateView):
    template_name = 'APP/login.html'

    def post(self, request):
        email = password = ""
        state = ""

        if request.POST:
            email = request.POST.get('email')
            password = request.POST.get('password')

            print(email, password)

            user = authenticate(username=request.POST.get('email'), password=request.POST.get('password'))
            if user is not None:
                login(request, user)

                return redirect('/login/index/')
            else:
                state = "Inactive account"
                # logging.StreamHandler
        return render(request, self.template_name, {'state': state, 'email': email})

class LogOutView(TemplateView):
    template_name = 'APP/logout.html'

    def logout(self, request):
        logout(request)
        return redirect('/login')

class IndexView(LoginRequiredMixin,TemplateView):
    login_url = '/login/'
    template_name = 'APP/index.html'

我目前在urls.py中有这些

app_name = 'app'
urlpatterns = [
    path('logout/', views.LogOutView.as_view(), name='logout'),
    path('login/', views.LoginView.as_view(), name='login'),
    path('login/index/', views.IndexView.as_view(), name='index'),

settings.py

LOGIN_URL = '/login'
LOGOUT_REDIRECT_URL = '/logout'

我的注销按钮在index.html页面上,如下所示:

<a href="logout/">
        <button>logout</button>
</a>

我不确定如何实现LoginRequiredMixin使其正常工作,并且单击注销按钮似乎并不能注销用户。

1 个答案:

答案 0 :(得分:1)

您需要覆盖get方法:

class LogOutView(TemplateView):
    template_name = 'APP/logout.html'

    def get(self, request, *args, **kwargs):
        logout(request)
        return redirect('/login')