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

你可能感兴趣的:(django)