重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这篇文章将为大家详细讲解有关Django 中怎么自定义用户模块,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
创新互联建站是一家专注于成都网站制作、网站建设、外贸网站建设与策划设计,密云网站建设哪家好?创新互联建站做网站,专注于网站建设十载,网设计领域的专业建站公司;建站业务涵盖:密云等地区。密云做网站价格咨询:13518219792Django中自带的User Model使用起来是比较方便的,但是通常我们的需求使用原生的User Model并不合适,或者少了一些必要的属性,或者多了些不必要的属性,这时就需要使用我们自己的User Model,自定义用户模块。
参考:Django官方文档 “Customizing authentication in Django” 部分,文档最后有完整的例子。
虽然自定义了用户模块,但是仍然可以使用Django原有的用户认证机制。
主要包含三个步骤
1. 定义自己的用户模块,包含用户类及用户Manager 类继承自Django中的AbstractBaseUser、BaseUserManager
2. 将自己定义的用户模块注册到Django的admin,即将自己的模块注册到Django的后台管理系统
3. 在settings.py中设置AUTH_USER_MODEL=“自定义用户模块类”
在自己的用户认证app的model.py中定义两个类,用户类和用户Manager类。
用户类:名字自定义,该例中名字为SysUser,该类继承自AbstractBaseUser,为了使用Django permission 框架,需再继承 PermissionsMixin。该类主要定义了用户的属性。
用户Manager类:名字自定义,该例中名字为SysUserManager,该类继承BaseUserManager,主要重定义create_user、create_superuser这两个函数。
点击(此处)折叠或打开
from django.db import models
from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser)
# Create your models here.
class SysUserManager(BaseUserManager):
def create_user(self, username, password=None):
"""
Creates and saves a User with the username
"""
user = self.model(
username=username,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, password):
"""
Creates and saves a superuser
"""
user = self.create_user(username,password)
user.is_admin = True
user.save(using=self._db)
return user
class SysUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=20, unique=True,)
full_name = models.CharField(max_length=20,default="姓名")
user_group = models.CharField(max_length=10,default="NULL")
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = SysUserManager()
USERNAME_FIELD = 'username'
#REQUIRED_FIELDS = ['full_name']
def __str__(self):
return self.username
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
在用户认证app的admin.py中必须定义的两个类,UserCreationForm和UserChangeForm,其他可以自定义的类参考Django官方文档。
点击(此处)折叠或打开
from django.contrib import admin
from django import forms
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from myauth.models import SysUser
# Register your models here.
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 = SysUser
fields = ('username', 'full_name', 'user_group','is_active','is_admin')
def clean_password2(self):
# Check that the two password entries match
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):
# Save the provided password in hashed format
user = super().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 = SysUser
fields = ('username', 'password', 'full_name', 'user_group','is_active','is_admin')
class SysUserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('username', 'full_name', 'user_group', 'is_active', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('username','full_name','user_group','is_active')}),
('Permissions', {'fields': ( 'is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2',)}
),
)
search_fields = ('username',)
ordering = ('username',)
filter_horizontal = ()
# Now register the new UserAdmin...
admin.site.register(SysUser, SysUserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
修改项目settings.py 中AUTH_USER_MODEL='myauth.SysUser'
点击(此处)折叠或打开
AUTH_USER_MODEL = 'myauth.SysUser'
关于Django 中怎么自定义用户模块就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。