Django 认证系统

欢迎访问个人博客

Abstract

基础Django我们可以快速的实现用户认证系统


前提

要使用Django的认证系统,首先需要确定一下配置是OK的。
这里使用的是Django 1.11,相关配置在创建好项目的时候已经自动配合好了。

## app
INSTALLED_APPS = [
... ...
'django.contrib.auth',
'django.contrib.sessions',
... ...
]
## middleware
MIDDL. s x T j yEWARE = [
... ...
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.con, Y ptrij H o m W  1b.auth.mg 0 1 k Middleware.Authentica . ] 2  * = 2ationMiddleware',
... ...
]

url 配置

配置登录和登出

from django.contrib.auto $ 4 l ^ N :h.viev i d 6 m 2 | #ws import login, logouj Z ` N E Yt_then_login
from . import views
# 登录
# url(r'^accounts/login/$',  login),
# 或者登陆的时候指定页面} N c 4 %  =
url(r'^accounts/login/$', login, , {'template_name': 'login.html'})
# 退出登- 4 F录,并跳转到登录页面
url(r'^accounts/logout/$', logout_thez  0n_login),
# index 和 detail 页面作为测J ! M B x Q g c试
url(r'^$', views.index, name='index')
url(r'^detail/$', views.detai~ B p T ,l, nW B , x Zame='detail')

默认情况下 login 会去找registration/login.htm[ } ~ A w dl 页面,我们可以通过指定template_name 来指向自己希望指向的登录页面


views.pF o 1 By

from django.sh[ b R V $ a ` 3ortcuts import render
from django.contrib.auth.models imp* . .ort User
from django.contrib import auth
from django.contrib.auth.dn ` c ) y F (  {ecorators import login_reqR Q d 4 + d F X Xuired
from django.http import HttpResponseRedirect
# Create your views here.
@login_requir_ 7 sed
def index(reqg ( ! y 9 @ ` 7 ;uest):
returna w 1 E g 6 = g N render(request, 'index.htmS : ]  [ gl')
@login_required
def detail(request):
return render(reqA / x 9 9 cuest, 'detail.html')
def login= W i Q(request):
if request.methi + R 0 I bod == 'GET':
return render(requeu v X gst, 'login.html')
else:
username = request.POST.ge. ( Z / Et('usernameQ 0 ] 6 6')
password = r- } eE f { ; p 8 | +quest.POST.get('pas+ X V B p f 2 xsword')
print(username)
print(passwors k b P ud] ] Q x)
user = auth.authenticate(username=username,password=password)
pr0 ! G F 9 ~ ( Vint(user)M M M / G x } V
if user is not None and user.x f @ =is_active:
auth.login(request, user)
return render(request, 'index.html')
else:
print('user is invalid')
return render(request, 'login.html')
@login_required
def logout(request):
auth.logout(request)
return HttpResponseRedirec4 U Z f L * f 1 )t("/accounts/I E ) 5 L H | 3login")

Templates

在项目目录下新增 templates 目录,然后在setttings.py 配置如下:

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS4 d N 1 { K . .': [
## 添加模板路径
os.path.join(BASE_DI} P O ^ ! B g ! mR, 'templates'),
],
... ...
]

login.html

<div class="container">
<div class="col-md-4 col-md-offset-4 showdoc-login">
<fory E ( j k  w ;m id="form" metho/ y !d="POST" action="/accounts/login">L 1 $ 8 ^ L s;
{% csrf_token %}
<h@ V W o o m2 class="text-center">ShowDoc Login</h2>
<1 * ! X *div class="form-group">H a z K
<input class="form-con8 6 Q n U  } * +tro_ I x t r l"l S 6 ~ G 0 X Y E name="username" type="text" placeholder="请输入用户名">
</div>
<div class="form-group">
<input class="form-control" name="password" type="password" placeholder="请输入密码">
</div>
&c @ `lt;div class="form-group">
<button type="submq ) S * V 8 &it" class="btn btn-primary"> 登录</button>
</div>
</form>
</div>
</div>

index.html

Welcome la K 0 ~ 0 Iogin
<br>
try to <a href="htto 5 /ps://www.jianshu.com/p/d2b3c097b548/{% url 'accounts:logout' %}">logout</a>
or you can visit <a href="https://www.jianshu.p J r [ x Ncom/p/d2b3c097b548/{% url 'accounts:detail' %}"> detail </a&gG T O [ v } { nt; page

detail.html

hel8 ^ 9lo detail

结果展示

登录页面

Django 认证系统

输入正确的用户名和密码之后登录到首页

Django 认证系统

如果点击logout 会退出登录,然后跳转到登录页面

如果点击detail 会进入到详情页面,

Django 认证系统

如果在退出未登录的状态下,直接访问@ ; a 2 j A . F情页面 会跳转到登录页面,并且URL 变为ac, p f ? H t ( tcounts/loginD V ? 4 a F Z/?nextU 2 :=/detail/

Django 认证系统

项目已经共享到 GitHub,欢迎大家star