django login和log

Django中的登入和登出即验证

1.得到用户输入的账号以及密码

	username = request.POST.get('username')
    password = request.POST.get('password')
    if not all([username,password]):
        return redirect(reverse('car:index'))

这里如果用户有账号或者密码没输的话,我们返回一个网页,这里的car:index就是我自己写的一个简单网页,网页你可以随便写。

2.将得到的账号和密码进入数据库进行校验
from django.contrib.auth import authenticate,login,logout
user = authenticate(username = username,password = password)

3.登入操作

if user is not None and user.is_active:
            login(request, user)
            request.session['username'] = user.username

            print(request.session.get('username','老张'))

            # return redirect(reverse('car:index'))
            return render(request,'xxx.html')

        else:
            # Show an error page
            return HttpResponse('false')

这里我们将得到用户输入的username存入session,然后输出这个session,在终端中查看,如果没有会默认输出老张,如果得到的是用户输入的username,则代表登入成功

4.登出操作

class LogoutView(View):
    def get(self,request):
        
        print(request.session.get('username', '老张'))
        logout(request)

        print(request.session.get('username', '老张'))
        
        return HttpResponse('登出成功')

我们在logout之前输出一下session,在logout之后输出一下session,如果第一次username是用户输入的username,第二次是老张,则代表登出成功。

完整代码:
class LoginView(View):

def post(self,request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    if not all([username,password]):
        return redirect(reverse('car:index'))
    #登陆验证
    user = authenticate(username = username,password = password)

    print(user.password)

    if user is not None and user.is_active:
        login(request, user)
        request.session['username'] = user.username

        print(request.session.get('username','老张'))

        # return redirect(reverse('car:index'))
        return render(request,'xxx.html')

    else:
        # Show an error page
        return HttpResponse('false')
        
class LogoutView(View):
    def get(self,request):
        
        print(request.session.get('username', '老张'))
        logout(request)

        print(request.session.get('username', '老张'))
        
        return HttpResponse('登出成功')

url:

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

你可能感兴趣的:(django login和log)