Django中用户登陆的实例:
逻辑流程
- 1、客户端发起请求,根据url规则会首先转至index函数,
- 2、在index函数上添加一个装饰器('@login_required',django自带)。加入该装饰器后,请求index函数时,django会跳转至 'accounts/login/' 。
- 3、在urls.py中设置将对 'accounts/login/' 的请求交给user_login函数处理。
- 4、user_login函数里定义验证条件,验证通过,返回首页。验证失败,返回登陆页面,并提示错误。
- 5、点击退出按钮,跳转至登陆页面
index.html
<html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Students CRM</h1> {% block page-content %} Welcome to The Students CRM {% endblock %} <div> {% if request.user.is_authenticated %} #如果登陆成功 <span>{{ request.user }}</span> #显示登陆名 {% else %} <span>登陆/注册</span> {% endif %} </div> <div> <a href="accounts/logout">退出</a> </div> </body> </html>
login.html
{% extends 'index.html' %} {% block page-content %} <form action="" method="post"> {% csrf_token %} <div> <input type="text" name="username"> </div> <div> <input type="password" name="password"> </div> <div> <input type="submit" value="login"> </div> </form> <div> {% if login_error %} <p style="color: red">{{ login_error }}</p> {% endif %} </div> {% endblock %}
views.py
#!_*_ coding:utf-8 _*_ from django.shortcuts import render,HttpResponseRedirect from django.shortcuts import HttpResponse # Create your views here. #调用django装饰器 from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate,login,logout @login_required #装饰器, def index(request): return render(request,'index.html') def user_login(request): #判断用户登陆 if request.method=='POST': user = authenticate(username=request.POST.get('username'),password=request.POST.get('password')) if user is not None: #user不为空,表示登陆成功 login(request,user) return HttpResponseRedirect('/') #登陆成功,跳转到首页 else: login_error='wrong username or password' return render(request,'login.html',{'login_error':login_error}) #登陆失败,返回错误信息 return render(request,'login.html') def user_logout(request): #退出登陆 logout(request) return HttpResponseRedirect('/')
urls.py
from django.conf.urls import url from django.contrib import admin from stu_crm import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.index), url(r'^accounts/login/',views.user_login), url(r'^accounts/logout/',views.user_logout), ]