Django用户登录

发表日期:2017年12月9日 02:43

使用Django函数登录验证

from django.contrib.auth import login,authenticate

def login_page(request):
    if request.method == "POST":
        username = request.POST.get("username","")
        password = request.POST.get("password","")
        user = authenticate(username=username,password=password)
        if user is not None:
            login(request,user)
            return render(request,'pages/index.html')
        else:
            return render(request, 'pages/login.html', {'msg': '账号或密码错误!'})
    elif request.method == "GET":
        return render(request, 'pages/login.html')

在模板里做验证

        {% if request.user.is_authenticated %}
        <div>WelCome!{{ request.user }}</div>
        {% else %}
            <div>User or Passwd EOEER</div>
        {% endif %}

使用Django类做登录验证

from django.contrib.auth import login,authenticate
from django.views.generic.base import View

class LoginView(View):
    def get(self,request):
        return render(request, 'pages/login.html',{'msg':'请输入账号密码!'})
    def post(self,request):
        username = request.POST.get("username", "")
        password = request.POST.get("password", "")
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            return render(request, 'pages/index.html')
        else:
            return render(request, 'pages/login.html', {'msg': '账号或密码错误!'})

url(r'^login/', views.LoginView.as_view(),name='login'),