Django自定义用户认证示例详解
作者:我的胡子有点扎 发布时间:2022-02-03 01:31:18
标签:django,自定义,用户认证
前言
Django附带的认证对于大多数常见情况来说已经足够了,但是如何在 Django 中使用自定义的数据表进行用户认证,有一种较为笨蛋的办法就是自定义好数据表后,使用OnetoOne来跟 Django 的表进行关联,类似于这样:
from django.contrib.auth.models import User
class UserProfile(models.Model):
"""
用户账号表
"""
user = models.OneToOneField(User)
name = models.CharField(max_length=32)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = verbose_name = "用户账号"
ordering = ['id']
这样做虽然可以简单、快速的实现,但是有一个问题就是我们在自己的表中创建一个用户就必须再跟 admin 中的一个用户进行关联,这简直是不可以忍受的。
admin代替默认User model
写我们自定义的 models 类来创建用户数据表来代替默认的User model,而不与django admin的进行关联,相关的官方文档在这里
👾戳我
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
class UserProfileManager(BaseUserManager):
def create_user(self, email, name, password=None):
"""
用户创建,需要提供 email、name、password
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
name=name,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, name, password):
"""
超级用户创建,需要提供 email、name、password
"""
user = self.create_user(
email,
password=password,
name=name,
)
user.is_admin = True
user.is_active = True
user.save(using=self._db)
return user
class UserProfile(AbstractBaseUser):
# 在此处可以配置更多的自定义字段
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
name = models.CharField(max_length=32, verbose_name="用户名称")
phone = models.IntegerField("电话")
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserProfileManager()
USERNAME_FIELD = 'email' # 将email 作为登入用户名
REQUIRED_FIELDS = ['name', 'phone']
def __str__(self):
return self.email
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
admin 配置
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = models.UserProfile
fields = ('email', 'name')
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = models.UserProfile
fields = ('email', 'password', 'name', 'is_active', 'is_admin')
def clean_password(self):
return self.initial["password"]
class UserProfileAdmin(BaseUserAdmin):
form = UserChangeForm
add_form = UserCreationForm
list_display = ('email', 'name', 'is_admin', 'is_staff')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('name',)}),
('Permissions', {'fields': ('is_admin', 'is_active', 'roles', 'user_permissions', 'groups')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'name', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ('groups', 'user_permissions','roles')
2.Django允许您通过AUTH_USER_MODEL配置来引用自定义的model设置来覆盖默认User模型,这个配置的配置方法为在 settings 中加入:AUTH_USER_MODEL = "APP.model_class"
,例如本例中我们需要在 setting 中加入以下配置:
AUTH_USER_MODEL = "app1.UserProfile"
3.部署
python manage.py makemigrations
python manage.py migrate
创建一个新用户,此时我们就可以用这个用户来登录 admin 后台了
python manage.py createsuperuser
效果如下:
自定义认证
那如果我们需要使用我们自己的认证系统呢,假如我们有一个 login 页面和一个 home 页面:
from django.shortcuts import render, HttpResponse, redirect
from django.contrib.auth import authenticate,login,logout
from app1 import models
from django.contrib.auth.decorators import login_required
def auth_required(auth_type):
# 认证装饰器
def wapper(func):
def inner(request, *args, **kwargs):
if auth_type == 'admin':
ck = request.COOKIES.get("login") # 获取当前登录的用户
if request.user.is_authenticated() and ck:
return func(request, *args, **kwargs)
else:
return redirect("/app1/login/")
return inner
return wapper
def login_auth(request):
# 认证
if request.method == "GET":
return render(request, 'login.html')
elif request.method == "POST":
username = request.POST.get('username', None)
password = request.POST.get('password', None)
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
_next = request.GET.get("next",'/crm')
return redirect('_next')
else:
return redirect('/app1/login/')
else:
return redirect('/app1/login/')
else:
pass
def my_logout(request):
# 注销
if request.method == 'GET':
logout(request)
return redirect('/app1/login/')
@login_required
def home(request):
# home page
path1, path2 = "Home", '主页'
if request.method == "GET":
return render(request, 'home.html', locals())
elif request.method == "POST":
pass
来源:http://www.cnblogs.com/forsaken627/p/8523371.html


猜你喜欢
- 模块a.py 想用 b.py中公有数据 cntb的python文件#!/usr/bin/env python# coding:utf8fro
- 1. 目标通过hadoop hive或spark等数据计算框架完成数据清洗后的数据在HDFS上爬虫和机器学习在Python中容易实现在Lin
- 分享一个 * 真网页拾色器(调色板),颜色丰富216色,使用方便。运行截图:<html id="container"
- 有的时候我们在使用pycharm编辑python,需要导入各种各样的包,这些包是不能直接使用的,需要先进行安装。否则就会出现模块导入错误。下
- 下面为大家举一个例子,请按照下面的步骤: (1)从http://home.gbsource.net/xuankong/dll.z
- JetBrainsMono 是 JetBrains 公司开发的一款开源字体,可免费商用。正如其名字带的Mono,即Monospaced Fo
- 定义变量什么是变量?在程序运行过程中,其值可以改变的量变量的定义?在 python 中,每个变量在使用前都必须赋值,变量赋值以后该变量才会被
- 研究了几天Adodb.stream和XMLHTTP的应用,找了不少很有趣的教程,下面的代码是将一个远程的页面,图片地址保存到本地的实例。将代
- 1、Node.js的单线程 非阻塞 I/O 事件驱动在 Java、PHP 或者.net 等
- 最近学习了SSD算法,了解了其基本的实现思路,并通过SSD模型训练自己的模型。基本环境torch1.2.0Pillow8.2.0torchv
- 在任何一个数据库中,查询优化都是不可避免的一个话题。对于数据库工程师来说,优化工作是最有挑战性的工作。MySQL开源数据库也不例外本站收录这
- 本文讲述了关于HTML5的data-*自定义属性。分享给大家供大家参考,具体如下:一、关于html元素的特性1.html元素都存在一些标准的
- Tkinter实现UI分页标签显示:Input页,红色部分为当前Frame的位置,下半部分为第一页的子标签;三页标签的显示内容各不相同。实现
- 下面的查询选择所有 date_col 值在最后 30 天内的记录。 mysql> SELECT something FROM tbl_
- 详解python中的文件与目录操作一 获得当前路径1、代码1>>>import os>>>print(&
- 本文实例讲述了js判断手机和pc端选择不同执行事件的方法。分享给大家供大家参考。具体如下:判断是否为手机:function isMobile
- SQL Server中的伪列下午看QQ群有人在讨论(非聚集)索引的存储,说,对于聚集索引表,非聚集索引存储的是索引键值+聚集索引键值;对于非
- 一、在CentOS上安装Python31.下载Python3.10源代码文件下载地址:https://www.python.org/down
- php二维数组排序测试数据 $arr = [
- 通过PyQt5实现设置一个小闹钟的功能,到了设置的时间后可以响起一段音乐来提醒。导入UI界面组件相关的模块from PyQt5.QtCore