#django登陆注销
任何一个动态系统基本离不开登录和注销,现在作为运维自动化的追随者使用python语言的较多。当然你坚持PHP是世界上最好的语言那我也没有办法。下面介绍下DJANGO框架的登录和注销
Views代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# _*_ coding:utf-8 _*_
from django.shortcuts import render,HttpResponseRedirect
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required#登陆后才能进入系统的模块
@login_required #登陆后才能进入系统

def acc_login(request):
login_err = ''
# print request.POST
if request.method == 'POST':
username = request.POST.get('inputUsername')
password = request.POST.get('inputPassword')
user = authenticate(username=username, password=password)
if user is not None:
login(request,user)
if user.is_active:
return HttpResponseRedirect('/')
login_err = "请检查用户名和密码是否正确"
return render(request, 'login.html', {
'login_err': login_err
})

def acc_logout(request):
logout(request)
return HttpResponseRedirect("/")

URLS代码

1
2
3
4
5
6
7
8
9
from django.conf.urls import url
from django.contrib import admin
from app1 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.index),
url(r'^index.html',views.index),
url(r'^login/$',views.acc_login),
url(r'^logout/$',views.acc_logout,name='acc_logout'), ####添加name作用是在前端使用{% url 'acc_logout' %}

前端index.html

1
2
3
4
5
6
7
8
9
<ul class="nav navbar-nav navbar-right">
{% if request.user.is_authenticated %} <!-- 判断用户是否已登录 -->
<li><a href="#">欢迎您:{{ request.user }}</a></li>
<li><a href="{% url 'acc_logout' %}">注销</a></li>
{% else %}
<li><a href="/login/">登陆</a></li>
<li><a href="/reg/">注册</a></li>
{% endif %}
</ul>

前端login.htm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div class="container">
<form class="form-signin" method="post">{% csrf_token %}
<h2 class="form-signin-heading">Please sign in</h2>
<label for="text" class="sr-only">Username</label>
<input type="text" name="inputUsername" class="form-control" placeholder="Username" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<span style="color: red;">{{ login_err }}</span>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>

Comments

2017-02-14