Django 认证系统
2017-08-31 本文已影响199人
菩提老鹰
Abstract
基础Django我们可以快速的实现用户认证系统
前提
要使用Django的认证系统,首先需要确定一下配置是OK的。
这里使用的是Django 1.11,相关配置在创建好项目的时候已经自动配合好了。
## app
INSTALLED_APPS = [
... ...
'django.contrib.auth',
'django.contrib.sessions',
... ...
]
## middleware
MIDDLEWARE = [
... ...
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
... ...
]
url 配置
配置登录和登出
from django.contrib.auth.views import login, logout_then_login
from . import views
# 登录
# url(r'^accounts/login/$', login),
# 或者登陆的时候指定页面
url(r'^accounts/login/$', login, , {'template_name': 'login.html'})
# 退出登录,并跳转到登录页面
url(r'^accounts/logout/$', logout_then_login),
# index 和 detail 页面作为测试
url(r'^$', views.index, name='index')
url(r'^detail/$', views.detail, name='detail')
默认情况下 login 会去找registration/login.html
页面,我们可以通过指定template_name
来指向自己希望指向的登录页面
views.py
from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
# Create your views here.
@login_required
def index(request):
return render(request, 'index.html')
@login_required
def detail(request):
return render(request, 'detail.html')
def login(request):
if request.method == 'GET':
return render(request, 'login.html')
else:
username = request.POST.get('username')
password = request.POST.get('password')
print(username)
print(password)
user = auth.authenticate(username=username,password=password)
print(user)
if user is not None and user.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 HttpResponseRedirect("/accounts/login")
Templates
在项目目录下新增 templates 目录,然后在setttings.py 配置如下:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
## 添加模板路径
os.path.join(BASE_DIR, 'templates'),
],
... ...
]
login.html
<div class="container">
<div class="col-md-4 col-md-offset-4 showdoc-login">
<form id="form" method="POST" action="/accounts/login">
{% csrf_token %}
<h2 class="text-center">ShowDoc Login</h2>
<div class="form-group">
<input class="form-control" name="username" type="text" placeholder="请输入用户名">
</div>
<div class="form-group">
<input class="form-control" name="password" type="password" placeholder="请输入密码">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary"> 登录</button>
</div>
</form>
</div>
</div>
index.html
Welcome login
<br>
try to <a href="{% url 'accounts:logout' %}">logout</a>
or you can visit <a href="{% url 'accounts:detail' %}"> detail </a> page
detail.html
hello detail
结果展示
登录页面
login-1.png输入正确的用户名和密码之后登录到首页
login-2.png如果点击logout
会退出登录,然后跳转到登录页面
如果点击detail
会进入到详情页面,
如果在退出未登录
的状态下,直接访问详情页面
会跳转到登录页面,并且URL 变为accounts/login/?next=/detail/
项目已经共享到 GitHub,欢迎大家star