1.auth模块的登录验证:
①只要登录的页面有用户名和密码就可以使用django提供的User表中的验证系统进行验证,可以把用户的账号和密码存到User对象表中,然后拿出来进行验证
1.from django.contrib import auth
2.def login(request):
if request.method == "POST":
username = request.POST.get("username")
pwd = request.POST.get("password")
# 如何判断用户名和密码对不对
user = auth.authenticate(username=username, password=pwd) #第一个是User表中的字段名 #称,第二个是传进来参数名称
if user:
# 将登录的用户封装到request.user
auth.login(request, user)
return redirect("/index/")
return render(request, "login.html")
3.def index(request):
# 取出封装到request.user中的用户名信息,返回浏览器中user是字符串,而请求来时候中间件会把user从数
#据库中取出来,转为一个对象
print(request.user.username)
print("=" * 120)
return render(request, "index.html")
如下图所示为源码
4.def logout(request): # 清楚request.user中信息
auth.logout(request)
return redirect("/login/")
5.from django.contrib.auth.decorators import login_required
@login_required # 如果没有登录,默认跳转到那个URL,在setting中配置
#LOGIN_URL = "/login/",否则执行index函数体中代码
def index(request):
print(request.user.username)
print("=" * 120)
ret = request.user.is_authenticated()
print(ret)
return render(request, "index.html")
2.User对象:
1.ret = user.is_authenticated() # 判断是否验证过了
2.def register(request):
from django.contrib.auth.models import User
User.objects.create(username="alex", password="alexdsb") #这个写法错误,以明文存入表,但是 #登录时候要进行转换,因此匹配不上密码
3.user_obj = User.objects.create_user(username="alex5", password="alexdsb")
# 校验密码是否正确
ret = user_obj.check_password("alex1234")
4. user_obj.set_password("alex3714") #修改密码
user_obj.save()
3.如何扩展自带的auth_user表:
1.from django.contrib.auth.models import User
class UserDetail(models.Model):
phone = models.CharField(max_length=11)
user = models.OneToOneField(to=User)
2.from django.contrib.auth.models import User, AbstractUser
class UserInfo(AbstractUser):
phone = models.CharField(max_length=11)
addr = models.CharField(max_length=128)