這篇文章將為大家詳細講解有關(guān)Django 中怎么自定義用戶模塊,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
創(chuàng)新互聯(lián)建站是一家專注于成都網(wǎng)站制作、網(wǎng)站建設、外貿(mào)網(wǎng)站建設與策劃設計,密云網(wǎng)站建設哪家好?創(chuàng)新互聯(lián)建站做網(wǎng)站,專注于網(wǎng)站建設十載,網(wǎng)設計領(lǐng)域的專業(yè)建站公司;建站業(yè)務涵蓋:密云等地區(qū)。密云做網(wǎng)站價格咨詢:13518219792Django中自帶的User Model使用起來是比較方便的,但是通常我們的需求使用原生的User Model并不合適,或者少了一些必要的屬性,或者多了些不必要的屬性,這時就需要使用我們自己的User Model,自定義用戶模塊。
參考:Django官方文檔 “Customizing authentication in Django” 部分,文檔最后有完整的例子。
雖然自定義了用戶模塊,但是仍然可以使用Django原有的用戶認證機制。
主要包含三個步驟
1. 定義自己的用戶模塊,包含用戶類及用戶Manager 類繼承自Django中的AbstractBaseUser、BaseUserManager
2. 將自己定義的用戶模塊注冊到Django的admin,即將自己的模塊注冊到Django的后臺管理系統(tǒng)
3. 在settings.py中設置AUTH_USER_MODEL=“自定義用戶模塊類”
在自己的用戶認證app的model.py中定義兩個類,用戶類和用戶Manager類。
用戶類:名字自定義,該例中名字為SysUser,該類繼承自AbstractBaseUser,為了使用Django permission 框架,需再繼承 PermissionsMixin。該類主要定義了用戶的屬性。
用戶Manager類:名字自定義,該例中名字為SysUserManager,該類繼承BaseUserManager,主要重定義create_user、create_superuser這兩個函數(shù)。
點擊(此處)折疊或打開
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'
關(guān)于Django 中怎么自定義用戶模塊就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
網(wǎng)站標題:Django中怎么自定義用戶模塊-創(chuàng)新互聯(lián)
分享地址:http://www.rwnh.cn/article0/dhhdoo.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供自適應網(wǎng)站、網(wǎng)站收錄、網(wǎng)站內(nèi)鏈、網(wǎng)站排名、App設計、企業(yè)網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容