django -- 登录验证
2017-09-22 20:22
316 查看
环境说明
Django:1.10Python:3.6
以 AbstractUser 方式扩展内置 User
# models.py 定义 model from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class UserProfile(AbstractUser): # 昵称 nick_name = models.CharField(max_length = 50, verbose_name = u"昵称", default="")
Note:内置 User 已经有了 username 和 password,要验证就是这两个
# admin.py 注册 model from django.contrib import admin from logre.models import UserProfile admin.site.register(UserProfile)
authenticate 进行用户验证
Note: 值得注意的是,authenticate 只是一个验证而已,需要另外使用 login() 进行登录,加入 session 中保持登录状态,怎样获得这个 session 信息的话,有待学习from django.shortcuts import render from django.contrib import auth def login(request): if request.method == 'POST': input_number = request.POST['input_username'] input_pwd = request.POST['input_pwd'] # 匹配成功的话返回用户对象 user = auth.authenticate(username=input_number,password=input_pwd) if user is not None and : # 更新登陆时间 now_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) user.last_login = now_time user.save() auth.login(request,user) return render(request,'index.html') return render(request,'login.html')
上面判断中出现的
user.is_active,用来判断用户名密码是否有效
当然,另外的 html 页面和 url 配置这里就不多说明了
注销
既然说到登录,注销就在这里一并记录了就像 login() 一样,auth 中也有 logout() 函数可以供我们使用
# views.py from django.contrib import auth def logout_view(request): auth.logout(request) return HttpResponseRedirect("/login/")
一样得配置相应的 url
常见问题
有时候,虽然数据库当中有 username 和 password 的存在,但是 authenticate 就是匹配不上,返回 None 值,可以尝试以下方法解决使用django自带的auth.user类,我们在modles下自建的user下的账号,有时候authenticate()会读取不到;
在账号注册的时候,插入函数要弄对,要用objects.create_user()函数,你用objects.create插入的时明文的,authenticate()当然会读取不到
如果我们直接导入 auth 的 login 时,使用的使用为 login(request,user),当你的函数名恰好为 login(request) 就会出错,修改过来就好
login() takes 1 positional argument but 2 were given
相关文章推荐
- Django学习系列之重写User模型和登录验证
- django自带的登录验证功能
- django项目开发模拟auth的做一个登录验证(一)
- Django学习笔记4 用户注册和身份验证、登录、注销、注册
- 关于Django的验证用户名密码登录
- django项目开发模拟auth的做一个登录验证(二)
- django 实现未经登录验证的url过滤
- 基于控制权限和登录验证跳转的django登录界面的实现
- Django自定义User模型和登录验证
- Django实战之用户验证登录
- Django自定义User模型和登录验证
- 07+. Django用户登录验证系统和登录注销
- 03 .29Django注册、 验证、登录
- Python+django实现邮箱验证登录
- Django(5) session登录注销、csrf及中间件自定义、django Form表单验证(非常好用)
- django 自定义登录验证逻辑
- Django 登录验证
- django 内置验证登录模块(auth login logout authenticate)测试
- Django笔记---用户注册和登录验证(1)--Post请求
- Django登录验证