中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Django 中怎么自定義用戶模塊

發布時間:2021-07-20 15:47:52 來源:億速云 閱讀:178 作者:Leah 欄目:編程語言

這篇文章將為大家詳細講解有關Django 中怎么自定義用戶模塊,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。

1、概述

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=“自定義用戶模塊類”

2、操作步驟

2.1 定義自己的用戶模塊

在自己的用戶認證app的model.py中定義兩個類,用戶類和用戶Manager類。
用戶類:名字自定義,該例中名字為SysUser,該類繼承自AbstractBaseUser,為了使用Django permission 框架,需再繼承 PermissionsMixin。該類主要定義了用戶的屬性。
用戶Manager類:名字自定義,該例中名字為SysUserManager,該類繼承BaseUserManager,主要重定義create_user、create_superuser這兩個函數。

點擊(此處)折疊或打開

  1. from django.db import models

  2. from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser)

  3. # Create your models here.



  4. class SysUserManager(BaseUserManager):

  5.     def create_user(self, username, password=None):

  6.         """

  7.         Creates and saves a User with the username

  8.         """


  9.         user = self.model(

  10.             username=username,

  11.         )



  12.         user.set_password(password)

  13.         user.save(using=self._db)

  14.         return user



  15.     def create_superuser(self, username, password):

  16.         """

  17.         Creates and saves a superuser

  18.         """

  19.         user = self.create_user(username,password)



  20.         user.is_admin = True

  21.         user.save(using=self._db)

  22.         return user



  23. class SysUser(AbstractBaseUser, PermissionsMixin):

  24.     username = models.CharField(max_length=20, unique=True,)

  25.     full_name = models.CharField(max_length=20,default="姓名")

  26.     user_group = models.CharField(max_length=10,default="NULL")

  27.     is_active = models.BooleanField(default=True)

  28.     is_admin = models.BooleanField(default=False)



  29.     objects = SysUserManager()



  30.     USERNAME_FIELD = 'username'

  31.     #REQUIRED_FIELDS = ['full_name']



  32.     def __str__(self):

  33.         return self.username



  34.     def has_perm(self, perm, obj=None):

  35.         "Does the user have a specific permission?"

  36.         # Simplest possible answer: Yes, always

  37.         return True



  38.     def has_module_perms(self, app_label):

  39.         "Does the user have permissions to view the app `app_label`?"

  40.         # Simplest possible answer: Yes, always

  41.         return True



  42.     @property

  43.     def is_staff(self):

  44.         "Is the user a member of staff?"

  45.         # Simplest possible answer: All admins are staff

  46.         return self.is_admin

2.2 注冊到Django Admin

在用戶認證app的admin.py中必須定義的兩個類,UserCreationForm和UserChangeForm,其他可以自定義的類參考Django官方文檔。

點擊(此處)折疊或打開

  1. from django.contrib import admin

  2. from django import forms

  3. from django.contrib.auth.models import Group

  4. from django.contrib.auth.admin import UserAdmin as BaseUserAdmin

  5. from django.contrib.auth.forms import ReadOnlyPasswordHashField

  6. from myauth.models import SysUser


  7. # Register your models here.



  8. class UserCreationForm(forms.ModelForm):

  9.     """A form for creating new users. Includes all the required

  10.        fields, plus a repeated password."""

  11.     password1 = forms.CharField(label='Password', widget=forms.PasswordInput)

  12.     password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)


  13.     class Meta:

  14.         model = SysUser

  15.         fields = ('username', 'full_name', 'user_group','is_active','is_admin')


  16.     def clean_password2(self):

  17.         # Check that the two password entries match

  18.         password1 = self.cleaned_data.get("password1")

  19.         password2 = self.cleaned_data.get("password2")

  20.         if password1 and password2 and password1 != password2:

  21.             raise forms.ValidationError("Passwords don't match")

  22.         return password2


  23.     def save(self, commit=True):

  24.         # Save the provided password in hashed format

  25.         user = super().save(commit=False)

  26.         user.set_password(self.cleaned_data["password1"])

  27.         if commit:

  28.             user.save()

  29.         return user



  30. class UserChangeForm(forms.ModelForm):

  31.     """A form for updating users. Includes all the fields on

  32.     the user, but replaces the password field with admin's

  33.     password hash display field.

  34.     """

  35.     #password = ReadOnlyPasswordHashField()


  36.     class Meta:

  37.         model = SysUser

  38.         fields = ('username', 'password', 'full_name', 'user_group','is_active','is_admin')



  39. class SysUserAdmin(BaseUserAdmin):

  40.     # The forms to add and change user instances

  41.     form = UserChangeForm

  42.     add_form = UserCreationForm


  43.     # The fields to be used in displaying the User model.

  44.     # These override the definitions on the base UserAdmin

  45.     # that reference specific fields on auth.User.

  46.     list_display = ('username', 'full_name', 'user_group', 'is_active', 'is_admin')

  47.     list_filter = ('is_admin',)

  48.     fieldsets = (

  49.         (None, {'fields': ('username','full_name','user_group','is_active')}),

  50.         ('Permissions', {'fields': ( 'is_admin',)}),

  51.     )

  52.     # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin

  53.     # overrides get_fieldsets to use this attribute when creating a user.

  54.     add_fieldsets = (

  55.         (None, {

  56.             'classes': ('wide',),

  57.             'fields': ('username', 'password1', 'password2',)}

  58.          ),

  59.     )

  60.     search_fields = ('username',)

  61.     ordering = ('username',)

  62.     filter_horizontal = ()


  63.     # Now register the new UserAdmin...



  64. admin.site.register(SysUser, SysUserAdmin)

  65. # ... and, since we're not using Django's built-in permissions,

  66. # unregister the Group model from admin.

  67. admin.site.unregister(Group)

2.3 修改AUTH_USER_MODEL

修改項目settings.py 中AUTH_USER_MODEL='myauth.SysUser'

點擊(此處)折疊或打開

  1. AUTH_USER_MODEL = 'myauth.SysUser'

關于Django 中怎么自定義用戶模塊就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

绥中县| 连城县| 红河县| 肃宁县| 库车县| 防城港市| 马山县| 枝江市| 抚顺县| 大厂| 东阳市| 福泉市| 清流县| 宝山区| 新兴县| 同德县| 张家港市| 泸州市| 隆林| 大冶市| 清远市| 和田市| 神池县| 乌什县| 武夷山市| 绥阳县| 新津县| 犍为县| 象州县| 卢氏县| 闽清县| 定日县| 汨罗市| 兴隆县| 庆安县| 迁安市| 贵州省| 荆门市| 河间市| 卫辉市| 皮山县|