您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關Django 中怎么自定義用戶模塊,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
Django中自帶的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 中怎么自定義用戶模塊就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。