因为django自带的用户认证系统是通过username、password, 已经无法满足现在大多数使用手机号和密码验证的需求,
所以:
A 需要扩展用户模型,添加telephone
B自定义验证方法,通过telephone获取用户,并验证密码
1、app01/models.py里面创建模型UserExtension, 一对一关联User
from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save class UserExtension(models.Model): user = models.OneToOneField( User, related_name="extension", on_delete= models.CASCADE ) telephone = models.CharField(max_length=11) school = models.CharField(max_length=100)
'''
sender 发送者
instance 代表调用的对象
created 是否是新创建
如果是新建User对象, 则User扩展对象UserExtension里面创建与User的关联
如果不是新建, User保存一次, 则User扩展对象UserExtension也自动保存
''' @receiver(post_save, sender = User) def create_user_extension( sender, instance, created, **kwargs ): if created: UserExtension.objects.create( user = instance) else: instance.extension.save()
2、执行makemigrations和migrate, 同步映射数据库
2、app01/views.py视图调用扩展模型,创建User和UserExtension对象
from django.shortcuts import render, HttpResponse from django.db import connection from django.contrib.auth.models import User def test(request): user = User.objects.create_user( username="zhiliao3", password="333333", email="zhiliao3@qq.com" ) user.extension.telephone = "18888688888" user.save() return HttpResponse("success")
通过url: http://127.0.0.1:8080/test访问后,数据库就创建User和UserExtension相关的数据:
3、若需要使用 telephone和password方式验证用户,需要自定义验证方法
from django.shortcuts import render, HttpResponse from django.db import connection from django.contrib.auth.models import User def my_authenticate(telephone, password): user = User.objects.filter( extension__telephone= telephone ).first() if user: is_correct = user.check_password( password) if is_correct: return user else: return None else: return None def test(request): # user = User.objects.create_user( username="zhiliao3", password="333333", email="zhiliao3@qq.com" ) # user.extension.telephone = "18888688888" # user.save() telephone = request.GET.get("telephone") password = request.GET.get("password") user = my_authenticate( telephone, password) if user: print("验证成功:%s" % user.username) else: print("验证失败!") return HttpResponse("success")
通过URL访问: http://127.0.0.1:8080/test/?telephone=18888688888&password=333333
打印结果如下:
erforming system checks...
System check identified no issues (0 silenced).
November 05, 2019 - 16:11:31
Django version 2.2.2, using settings 'untitled1019.settings'
Starting development server at http://127.0.0.1:8080/
Quit the server with CTRL-BREAK.
验证成功:zhiliao3