环境:PYTHON2.7,DJANGO1.9
1、帐号密码的创建,只处创建的为超级用户,默认可以登陆django的管理界面
2、配置DJANGO的项目文件
配置settings.py,增加
# LOGIN_URL = 'accounts/login/' django项目页面默认的LOGIN_URL,因为是默认的,如果不改,可以不用添加
LOGIN_REDIRECT_URL = '/django' #登陆以后跳转的URL
配置urls.py,增加
url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
用DJANGO内置的方法处理这个登陆的请求
增加templates\registration\login.html
由于该方法django.contrib.auth.views.login默认会调用项目的templates\registration\login.html,需要创建这个页面的表单
如果不用这个路径的HTML需要在上面的方法指定HTML文件
(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'tests/login.html'}),
实验中采用了默认的路径,项目的templates\registration\login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<div class="container">
<form class="form-signin" action="/accounts/login/" method="post">{% csrf_token %} <!--csrf_token:生成令牌-->
<h2 class="form-signin-heading" align="center">登录系统</h2>
<label for="inputUsername" class="sr-only">username</label>
<input type="text" name="username" id="inputUsername" class="form-control" placeholder="username" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> 记住密码
</label>
</div>
<br />
<button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
<br />
<span style="color: red;">{{ login_err }}</span>
</form>
</div> <!-- /container -->
配置views.py,增加
from django.contrib.auth.decorators import login_required #为了能够使用django自带的装饰器 @login_required
然后到添加到方法前面,这样的目的是让用户访问带有这个方法的URL的时候需要登陆
3、登陆测试
输入原来不需要登陆就能访问的DJANGO项目URL回车,此时跳转到登陆界面
输入创建的用户名和密码,登陆成功,实现了登陆访问,并且跳转到了settings指定的URL,LOGIN_REDIRECT_URL = '/django'