1. 程式人生 > >django 使用者登入與退出

django 使用者登入與退出

urls.py

from django.conf.urls import url
from users.views import LoginView,LogoutView

urlpatterns = [
    url(r'^login/$', LoginView.as_view(),name="login"),
    url(r'^logout/$', LogoutView.as_view(),name="logout"),
    ……
]

forms.py

class LoginForm(forms.Form):
    username=forms.CharField(required
=True)
password=forms.CharField(required=True,min_length=5)

views.py

from django.http.response import HttpResponse,HttpResponseRedirect
from django.shortcuts import render
from django.contrib.auth import authenticate,login,logout
from django.views.generic.base import View
from django.core.urlresolvers import
reverse from .froms import LoginForm class LogoutView(View): """ 使用者登出 """ def get(self,request): logout(request) return HttpResponseRedirect(reverse("index")) class LoginView(View): """ 使用者登入 """ def get(self,request): return render(request, 'login.html'
) def post(self,request): login_form=LoginForm(request.POST) if login_form.is_valid(): user_name = request.POST.get('username', None) pass_word = request.POST.get('password', None) user = authenticate(username=user_name, password=pass_word) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "login.html", {"msg": "使用者未啟用"}) else: return render(request, "login.html", {"msg": "使用者名稱或密碼錯誤"}) else: return render(request, "login.html", {"login_form":login_form})