用户登录、登出、登录限制
1、在app01/models.py里面定义User模型,通过AbstractBaseUser扩展用户模型
from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin from django.contrib.auth import get_user_model class UserManager(BaseUserManager): def _create_user(self , telephone, username, password, **kwargs): if not telephone: raise ValueError("必须要传递手机号码!") if not password: raise ValueError("必须要传递密码") user = self.model( telephone = telephone, username= username , **kwargs) user.set_password( password ) user.save() return user def create_user(self, telephone, username, password, **kwargs): # kwargs['is_superuser'] = False return self._create_user( telephone = telephone, username=username, password = password, **kwargs ) def create_superuser(self, telephone, username, password, **kwargs): # kwargs['is_superuser'] = True return self._create_user( telephone = telephone, username=username, password = password, **kwargs ) class User(AbstractBaseUser, PermissionsMixin): telephone = models.CharField(max_length=11, unique=True) email = models.CharField(max_length=100, unique=True) username = models.CharField(max_length=100) is_active = models.BooleanField(default=True) USERNAME_FIELD = "telephone" #USERNAME_FIELD作用,是执行authenticate验证, username参数传入后,实际校验的是telephone字段 REQUIRED_FIELDS = [] objects = UserManager() def get_full_name(self): return self.username def get_short_name(self): return self.username class Article(models.Model): title = models.CharField(max_length=100) content = models.TextField() # author = models.ForeignKey( User, on_delete= models.CASCADE ) #get_user_model()会自动获取settings.py里面 AUTH_USER_MODEL,这样不管你定义的那个User,都可以自动获取,更安全 author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
2、在settings.py设置用户模型用哪个
AUTH_USER_MODEL = "app01.User"
3、在视图里调用User模型,进行登录、登出、登录限制
from django.shortcuts import render, HttpResponse, reverse,redirect from django.db import connection from app01.models import User from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from app01.forms import LoginForm def test(request): #创建用户 # User.objects.create_user( telephone="15555655555", password="555555", username="zhiliao5" ) #用认证 user = authenticate(request, username="15555655555", password="555555") if user: print(user.username) print("验证成功!") else: print("验证失败!") return HttpResponse("继承AbstractUser扩展用户") def my_login(request): if request.method == "GET": return render(request, "login.html") else: print("提交的数据为:"); print(request.POST) form = LoginForm(request.POST) if form.is_valid(): telephone = form.cleaned_data.get("telephone") password = form.cleaned_data.get("password") remember = form.cleaned_data.get("remember") user = authenticate(request, username =telephone, password=password) if user and user.is_active: login(request, user) if remember: request.session.set_expiry(None) else: request.session.set_expiry(0) return HttpResponse("登录成功!") else: return HttpResponse("手机号码或者密码错误!") else: print(form.errors) return redirect( reverse("login") ) def my_logout(request): logout(request) return HttpResponse("成功退出") @login_required(login_url="/login/") def profile(request): return HttpResponse("这是个人中心,只有登录了以后才能查看到!")
4、在urls.py里面定义路由
from django.contrib import admin from django.urls import path from app01 import views as app01_views urlpatterns = [ path('admin/', admin.site.urls), path("test/", app01_views.test), path("login/", app01_views.my_login, name = "login"), path("logout/", app01_views.my_logout, name = "logout"), path("profile/", app01_views.profile, name="profile"), ]
5、登录,无 “记住我” 功能, 登录成功后,关闭浏览器,session就过期
扫描二维码关注公众号,回复:
7775264 查看本文章
![](/qrcode.jpg)
6、登录,带 “记住我” 的功能, 登录成功后,session过期时间为两个星期
6、登出后, session的创建时间和过期时间相等,等于session无效
7、登录限制