day76
1 auth组件介绍
2 auth组件内置属性方法
3 User对象的属性
4 扩展默认的auth_user表
5 自定义中间表(中介模型)
## 1 auth组件介绍 ```python 1 我们需要实现包括用户注册、用户登录、用户认证、注销、修改密码等功能,内置了强大的用户认证系统--auth,是一个app ``` ## 2 auth组件内置属性方法 数据迁移以后使用 ### authenticate用户认证 ```python from django.contrib import auth def login(request): if request.method=='GET': return render(request,'login.html') else: name=request.POST.get('name') password=request.POST.get('password') # 明文 ## 方案行不通,密码是密文的,永远匹配不成功 # user=User.objects.filter(username=name,password=password) ## 使用此方案 ## 第一个参数必须是request对象 ##username和password user=auth.authenticate(request,username=name,password=password) if user: return HttpResponse('登录成功') else: return HttpResponse('用户名或密码错误') ``` ### login ```python auth.login(request,user) # 表示用户登录了 # 1 存了session # 2 以后所有的视图函数,都可以使用request.user,它就是当前登录用户 ``` ### logout ```python def logout(request): # 后续再访问视图函数,就没有当前登录用户了request.user(匿名用户AnonymousUser) auth.logout(request) return redirect('/index/') ``` ### is_authenticated ```python # is_authenticated 返回True或者False,判断用户是否登录 # 用在视图中 if request.user.is_authenticated: print('用户登录了') else: print('用户没有登录,匿名用户') # 用在模板中 {% if request.user.is_authenticated %} {{ request.user.username }} 登录了 {% else %} <a href="/login/">滚去登录</a> {% endif %} ``` ### login_requierd ```python 1 装饰器,装饰在视图函数上,只要没有登录,就进不来 # 必须登录后才能访问 @login_required(login_url='/login/') ``` ### create_user ```python # 使用内置的create_user或者create_superuser方法 user=User.objects.create_user(username=name,password=password) # user=User.objects.create_superuser(username=name,password=password) ``` ### check_password ```python ## 有了用户,校验密码是否正确 # 先获取到用户对象 user = User.objects.filter(username=name).first() # 判断密码是否正确 flag=user.check_password(password) ``` ### set_password ```python def change_password(request): if request.method == 'GET': return render(request, 'change_pwd.html') else: old_pwd = request.POST.get('old_pwd') new_pwd = request.POST.get('new_pwd') re_new_pwd = request.POST.get('re_new_pwd') if request.user.check_password(old_pwd): # 密码正确再修改 request.user.set_password(new_pwd) # 记住保存(****) request.user.save() return redirect('/login/') else: return HttpResponse('原来密码错误') ``` ## 3 User对象的属性 ```python is_staff : 用户是否拥有网站的管理权限,是否可以登录到后台管理 is_superuser:是否是超级管理员(如果is_staff=1,可以任意增删查改任何表数据) is_active : 是否允许用户登录, 设置为 False,可以在不删除用户的前提下禁止用户登录(三次密码输入错误禁用用户) ``` ## 4 扩展默认的auth_user表 ```python 1 内置的auth_user表,要加字段,加不了,扩展该表 -方式一:一对一 -方式二,通过继承 # 方式二:通过继承,一定要记住在setting中配置 ## 重点:使用这种方式,一开始就要用 from django.contrib.auth.models import AbstractUser class User(AbstractUser): # id=models.AutoField(primary_key=True) # username = models.CharField(max_length=128) phone = models.CharField(max_length=32) addr = models.CharField(max_length=32) ## setting.py中 AUTH_USER_MODEL = "app01.User" ``` ### 如果项目一开始没有扩展auth_user表,后期想扩展的操作步骤 ```python 1 备份--删库--->重新创建出数据库 2 所有app的数据迁移记录删除migrations下除了__init__.py都删除 3 (重要)去源码中删除auth和admin 这俩app的migrations下,除了__init__.py都删除 4 数据迁移,同步到数据库 5 备份的数据,恢复回去 ``` ## 5 自定义中间表(中介模型) ```python 1 多对多关系中,第三张表的建立 -默认使用ManyToMany,自动创建 -使用中介模型 -既手动创建第三张表,又要使用好用的查询 -完全自己写第三张表 # 使用中介模型 class Author(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() author_detail = models.OneToOneField(to='AuthorDatail', to_field='nid', unique=True, on_delete=models.CASCADE) class AuthorDatail(models.Model): nid = models.AutoField(primary_key=True) telephone = models.BigIntegerField() birthday = models.DateField() addr = models.CharField(max_length=64) class Book(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) price = models.DecimalField(max_digits=5, decimal_places=2) publish_date = models.DateField() publish = models.ForeignKey(to='Publish', to_field='nid', on_delete=models.CASCADE) # 当前在哪个表中,元组中的第一个参数就是 表名_id authors=models.ManyToManyField(to='Author',through='AuthorToBook',through_fields=('book_id','author_id')) def __str__(self): return self.name class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() class AuthorToBook(models.Model): nid = models.AutoField(primary_key=True) book_id = models.ForeignKey(to=Book, to_field='nid', on_delete=models.CASCADE) author_id = models.ForeignKey(to=Author, to_field='nid', on_delete=models.CASCADE) date=models.DecimalField() # s1.py import os if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE", "day76.settings") import django django.setup() from app01 import models # 梦这本书是lqz和egon写的 # book=models.Book.objects.get(pk=1) # # book.authors.add(1,2) # 用不了了 # # 只能手动写 # models.AuthorToBook.objects.create(book_id_id=1,author_id_id=1) # models.AuthorToBook.objects.create(book_id_id=1,author_id_id=2) # 梦这本书所有的作者 # book = models.Book.objects.get(pk=1) # res=models.AuthorToBook.objects.filter(book_id=book) # print(res) # book = models.Book.objects.get(pk=1) # print(book.authors.all()) # 梦这本书是lqz和egon写的 add ,remove, clear,set # 但是连表操作,book.authors这些都能用 book = models.Book.objects.get(pk=1) book.authors.add(1,2) # 不能用了 ```
# urls.py from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.login), path('order/', views.order), path('logout/', views.logout), path('index/', views.index), path('register/', views.register), path('change_pwd/', views.change_pwd), ]
# views,py from django.shortcuts import render, HttpResponse, redirect # Create your views here. from django.contrib.auth.models import User from django.contrib import auth from django.contrib.auth.decorators import login_required def login(request): if request.method == 'GET': return render(request, 'login.html') else: username = request.POST.get('name') password = request.POST.get('password') # 此处获取的是明文密码 # user = User.objects.filter(username=username, password=password) # 数据库中的密码为密文,此处匹配不会成功 user = auth.authenticate(request, username=username, password=password) # 第一个参数必须是request对象,匹配成功则返回user对象,匹配失败返回none user_0 = User.objects.filter(username=username).first() # 获取用户对象 flag = user_0.check_password(password) # check_password 判断密码是否正确 if flag: auth.login(request, user) # 参数:request,user对象 # auth.login() # 表示用户已登录,存入session,之后所有的视图函数都可以使用request.user即当前登录用户 url = request.GET.get('next') if url: return redirect(url) else: return redirect('/index/') else: return HttpResponse('用户名或密码错误') @login_required(login_url='/login/') # 装饰器为必须登录后才能访问。如果没有登录,则重定向到login_url的地址 def order(request): print(request.user) if request.user.is_authenticated: # is_authenticated()判断是否有用户登录,如果是AbstractBaseUser类的对象则一直返回true print('用户已登录') else: print('用户没有登录,为匿名用户') # 如果是匿名用户则一直返回false return render(request, 'order.html') def logout(request): auth.logout(request) # 后续再访问视图函数,就没有当前登录用户了,此时request.user为AnonymousUser匿名用户 print(request.user) return redirect('/index/') def register(request): if request.method == 'GET': return render(request, 'register.html') else: username = request.POST.get('name') password = request.POST.get('password') re_password = request.POST.get('re_password') if re_password == password: # User.objects.create(username=username, password=password) # 不能通过create来创建用户,因为此处的password为明文 User.objects.create_user(username=username, password=password) # 通过create_user来创建 return redirect('/login/') else: return HttpResponse('密码不一致。') def change_pwd(request): if request.method == 'GET': return render(request, 'change_pwd.html') else: old_pwd = request.POST.get('old_pwd') new_pwd = request.POST.get('new_pwd') re_new_pwd = request.POST.get('re_new_pwd') if request.user.check_password(old_pwd): if new_pwd == re_new_pwd: request.user.set_password(new_pwd) request.user.save() # 需要手动保存到数据库 return redirect('/login/') else: return HttpResponse('密码不一致') else: return HttpResponse('原密码错误') def index(request): return render(request, 'index.html')
# models.py from django.db import models # Create your models here. # # 方式一,通过一对一实现 # from django.contrib.auth.models import User # class UserDetail(models.Model): # phone = models.CharField(max_length=32) # addr = models.CharField(max_length=32) # user= models.OneToOneField(to=User) # 方式二:通过继承,一定要记住在setting中配置 # 重点:使用这种方式,一开始就要用 from django.contrib.auth.models import AbstractUser class User(AbstractUser): # 继承AbstractUser # id=models.AutoField(primary_key=True) # username = models.CharField(max_length=128) phone = models.CharField(max_length=32) addr = models.CharField(max_length=32) # # class Author(models.Model): # nid = models.AutoField(primary_key=True) # name = models.CharField(max_length=32) # age = models.IntegerField() # author_detail = models.OneToOneField(to='AuthorDatail',to_field='nid',unique=True,on_delete=models.CASCADE) # # # class AuthorDatail(models.Model): # nid = models.AutoField(primary_key=True) # telephone = models.BigIntegerField() # birthday = models.DateField() # addr = models.CharField(max_length=64) # # # class Book(models.Model): # nid = models.AutoField(primary_key=True) # name = models.CharField(max_length=32) # price = models.DecimalField(max_digits=5, decimal_places=2) # publish_date = models.DateField() # # publish = models.ForeignKey(to='Publish',to_field='nid',on_delete=models.CASCADE) # # authors=models.ManyToManyField(to='Author') # def __str__(self): # return self.name # # class Publish(models.Model): # nid = models.AutoField(primary_key=True) # name = models.CharField(max_length=32) # city = models.CharField(max_length=32) # email = models.EmailField() # # # # # 最土的方式,手动建第三张表 # class AuthorToBook(models.Model): # nid = models.AutoField(primary_key=True) # book_id=models.ForeignKey(to=Book,to_field='nid',on_delete=models.CASCADE) # author_id=models.ForeignKey(to=Author,to_field='nid',on_delete=models.CASCADE) # # # # 使用中介模型 class Author(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() author_detail = models.OneToOneField(to='AuthorDatail', to_field='nid', unique=True, on_delete=models.CASCADE) class AuthorDatail(models.Model): nid = models.AutoField(primary_key=True) telephone = models.BigIntegerField() birthday = models.DateField() addr = models.CharField(max_length=64) class Book(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) price = models.DecimalField(max_digits=5, decimal_places=2) publish_date = models.DateField() publish = models.ForeignKey(to='Publish', to_field='nid', on_delete=models.CASCADE) # 当前在哪个表中,元组中的第一个参数就是 表名_id authors=models.ManyToManyField(to='Author', through='AuthorToBook', through_fields=('book_id','author_id')) def __str__(self): return self.name class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() # 最土的方式,纯手动建第三张表 class AuthorToBook(models.Model): nid = models.AutoField(primary_key=True) book_id = models.ForeignKey(to=Book, to_field='nid', on_delete=models.CASCADE) author_id = models.ForeignKey(to=Author, to_field='nid', on_delete=models.CASCADE) date = models.DateField()

浙公网安备 33010602011771号