Django本身内建这样的功能,admin管理页面就使用了这样的验证机制,admin管理页面就有Groups和Users选项
需要在models.py中导入
from django.contrib.auth.models import User
#auth.User默认的字段只有username、password、email、first_name、last_name,一般是不够,可以增加,但不是在User中加,而是创建用户类Profile。用新的model一对一连接一起
class Profile(models.Model):
user = models.OneToOneField(User, on_delete= models.CASCADE)#一对一连接
height = models.PositiveIntegerField(default=160)
male = models.BooleanField(default=False)
website = models.URLField(null=True)
def __unicode__(self):
return self.user.username
区别是django.contrib.auth.models中的类还是models中定义的User的类,主要看view.py中函数怎么引用
user = models.User.objects...#这就是自己定义的User
user = User.objects...#这就是取自django.contrib.auth.models
django.contrib.auth提供3个主要函数:
- authenticate
- login
- logout
from django.contrib.auth import authenticate
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.contrib import messages
@login_required(login_url='/login_2/')
def userinfo(request):
if request.user.is_authenticated():#检查用户是否登录
username = request.user.username
try:
user =User.objects.get(username=username)#找到USer的应用实例,再以此为参数,放到Profile中寻找
userinfo = Profile.objects.get(user=user)
except:
pass
template = get_template('one/agriculture/userinfo.html')
request_context = RequestContext(request) # 使用{% csrf_token %}需要用RequestContext
request_context.push(locals())
html = template.render(request_context)
return HttpResponse(html)
def login_2(request):
if request.method == 'POST':
login_form = LoginForm(request.POST)
if login_form.is_valid():
login_name=request.POST['username'].strip()
login_password = request.POST['password']
user = authenticate(username=login_name,password=login_password)
if user is not None:
if user.is_active:
auth.login(request,user)#把此用户的数据存入session中
print "success"
messages.add_message(request,messages.SUCCESS,'成功登陆了')#使用了django的信息显示框架 message framework
return HttpResponseRedirect('/userinfo/')
else:
messages.add_message(request,messages.WARNING,"账号尚未启动")
else:
messages.add_message(request,messages.WARNING,"登陆失败")
else:
messages.add_message(request,messages.INFO,"请检查输入的字段内容")
else:
login_form = LoginForm()
template = get_template('one/agriculture/login.html')
request_context = RequestContext(request)
request_context.push(locals())
html = template.render(request_context)
return HttpResponse(html)
def logout(request):
auth.logout(request)#运用auth函数功能,不需要自己处理Session变量
messages.add_message(request,messages.INFO,"成功注销了")
return redirect('/userinfo/')
-
前面的decorator@login_required(login_url='/login_2/')是auth验证机制提供一个方便的用法,用来告诉Django接下来处理的函数内容需要登录才能浏览,没有登录就想执行这一页,就转到登录括号中指定的login_url网址:
-
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for message in messages %}
<div class='alert alert-{{message.tags}}'>{{ message }}</div>
{% endfor %}
<!--主要是结合message framework 用-->
<p>登陆我的农商</p>
<form action="/login_2/" method="post">
{% csrf_token %}
<table>
{{ login_form.as_table }}
</table>
<input type="submit" value="登陆" />
</form>
</body>
</html>
- 使用login_form = LoginForm()需要在models.py中定义该类,但不要admin.py中admin.site.register,凡是forms.Form的都不需要,只有models.Model要
class LoginForm(forms.Form):
username = forms.CharField(label='姓名',max_length=10)
password = forms.CharField(label='密码',widget = forms.PasswordInput())