解决Django扩展用户表后新表内增加用户密码存储为明文

解决Django扩展用户表后新表内增加用户密码存储为明文[Python基础]

问题:
最近在使用Django时,扩展了django自身的auth_user表,大体格式如下:

from django.contrib.auth.models import User as AbstractUser

class Users(AbstractUser):

"""

此表记录系统使用人员详细信息

"""

Users_Name = AbstractUser.username

# 部门编号

Users_Group = models.ForeignKey(UserGroup, models.CASCADE, db_column="User_Group", null=True, verbose_name="部门编号")

# 当前用户的权限是第几级别

Users_Power = models.ForeignKey(UserPower, models.CASCADE, db_column="User_Power", null=True, verbose_name="用户权限")

# 是否已被锁定

UserNotActive = models.BooleanField(db_column="IsLock", default=0, verbose_name="是否锁定")

整体表格是在原表的基础上多加了几列数据,但完成后发现,在django自带的Web后台中从新表增加用户时,密码会被默认使用明文存储至数据库:

存储到数据库就类似下图所示:

 Django前端正常密码输入位置应类似下图:

数据库中正确的存储应类似下图:

解决方法:

UserAdmin源码主要包含了auth_user表格的信息,可以在继承UserAdmin类的基础上,重写对应的所需数据。如UserAdmin部分源码如下:

class UserAdmin(admin.ModelAdmin):

add_form_template = "admin/auth/user/add_form.html"

change_user_password_template = None

fieldsets = (

(None, {"fields": ("username", "password")}),

(_("Personal info"), {"fields": ("first_name", "last_name", "email")}),

(_("Permissions"), {

"fields": ("is_active", "is_staff", "is_superuser", "groups", "user_permissions"),

}),

(_("Important dates"), {"fields": ("last_login", "date_joined")}),

)

add_fieldsets = (

(None, {

"classes": ("wide",),

"fields": ("username", "password1", "password2"),

}),

)

form = UserChangeForm

add_form = UserCreationForm

change_password_form = AdminPasswordChangeForm

list_display = ("username", "email", "first_name", "last_name", "is_staff")

list_filter = ("is_staff", "is_superuser", "is_active", "groups")

search_fields = ("username", "first_name", "last_name", "email")

ordering = ("username",)

filter_horizontal = ("groups", "user_permissions",)

可以在UserAdmin的基础上,将自己Django项目中对应app的admin视图下,修改为下列信息:

class UsersAdmin(UserAdmin):

# 显示元组,携带的字段均为扩展字段,使用了fieldsets后也可不再修改该元组

list_display = ("Users_Name", "Users_Group", "Users_Phone", "Users_Power", "UserNotActive")

# 搜索数据时使用的元组, 携带的字段均为扩展字段

search_fields = ("Users_Name", "Users_Group", "Users_Phone", "Users_Power", "UserNotActive")

# 排序依据

ordering = ("Users_Group",)

# fieldsets 主要用于字段分组,仅应用于显示

fieldsets = (

# 此处保留UserAdmin中的password字段,以此保证在新增用户时避免出现明文存储的问题

(gettext_lazy("基本信息"), {"fields": ("username", "password", "first_name", "last_name", "email", "Users_Phone")}),

(gettext_lazy("权限信息"), {"fields": ("Users_Group", "Users_Power", "UserNotActive")}),

(gettext_lazy("日期信息"), {"fields": ("last_login", "date_joined")}),

)

admin.site.register(models.Users, UsersAdmin)

以上是 解决Django扩展用户表后新表内增加用户密码存储为明文 的全部内容, 来源链接: utcz.com/z/537713.html

回到顶部