Django自定义User模型和登录验证
来源:互联网 发布:sql between 编辑:程序博客网 时间:2024/05/21 10:49
http://www.redicecn.com/html/blog/Django/2012/0325/385.html
用户表已存在(与其他App共用),不能再使用Django内置的User模型和默认的登录认证。但是还想使用Django的认证框架(真的很方便啊)。
两个步骤:
1)自定义Use模型,为了区分系统的User模型,命名为Account。
- class Account(models.Model):
- business_email = models.EmailField()
- business_password = models.CharField(max_length=20)
- contact_first_name = models.CharField(max_length=30)
- contact_last_name = models.CharField(max_length=30)
- is_active = models.BooleanField()
- def is_authenticated(self):
- return True
- def hashed_password(self, password=None):
- if not password:
- return self.business_password
- else:
- return hashlib.md5(password).hexdigest()
- def check_password(self, password):
- if self.hashed_password(password) == self.business_password:
- return True
- return False
- class Meta:
- db_table = "bussinesses"
2)自定义登录验证后台,并加入AUTHENTICATION_BACKENDS。
- # auth.py
- from coocaca.myauth.models import Account
- class MyCustomBackend:
- def authenticate(self, business_email=None, business_password=None):
- try:
- user = Account.objects.get(business_email=business_email)
- except Account.DoesNotExist:
- pass
- else:
- if user.check_password(business_password):
- return user
- return None
- def get_user(self, user_id):
- try:
- return Account.objects.get(pk=user_id)
- except Account.DoesNotExist:
- return None
在settings.py中加入该验证后台:
- AUTHENTICATION_BACKENDS = (
- 'coocaca.myauth.auth.MyCustomBackend',
- )
这样Django就会使用MyCustomBackend作为登录验证后台。
验证通过后返回的是我们自定义的Account模型,并且request.user中获取的也是我们的Account模型(这正是MyCustomBackend中get_user方法的功能)。
- Django自定义User模型和登录验证
- Django学习笔记 — 自定义User模型
- django 1.7 自定义用户user模型的三种方法
- django 1.7 自定义用户user模型的三种方法
- django 自定义 USER
- django自定义USER
- 07+. Django用户登录验证系统和登录注销
- Django中扩展User模型
- Django登录验证
- django -- 登录验证
- Django使用自定义验证
- Django笔记---用户注册和登录验证(1)--Post请求
- Django笔记---用户注册和登录验证(2)--数据库储存
- Django 笔记 user 注册 登录 及 权限
- django 用户登录及验证
- Django实现登录验证功能
- Django学习笔记 扩展User模型
- CAS自定义登录验证
- Minor GC 和 Full GC输出日志格式
- 关于MFC未来的感悟
- Eclipse+Maven+Mybatis使用
- c面试
- 向tableLayoutPanel中动态添加panel
- Django自定义User模型和登录验证
- Spring的AOP思想研究和实现
- 浮点运算转换成整数运算
- 记事本使用技巧
- IOS网络编程(一)
- spring配置文件在打包使用时找到不路径问题
- dmalloc doesn't show log when a program compiled with pthread
- Windows下如何查看被占用的端口号及如何释放进程
- Source Insight使用教程