中文字幕日韩精品一区二区免费_精品一区二区三区国产精品无卡在_国精品无码专区一区二区三区_国产αv三级中文在线

Django中怎么自定義用戶模塊-創(chuàng)新互聯(lián)

這篇文章將為大家詳細講解有關(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)站價格咨詢:13518219792

1、概述

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

2、操作步驟

2.1 定義自己的用戶模塊

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

點擊(此處)折疊或打開

  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'

關(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)

搜索引擎優(yōu)化
兖州市| 光泽县| 延川县| 罗江县| 永善县| 习水县| 长沙市| 永新县| 甘泉县| 荃湾区| 祁东县| 共和县| 海丰县| 茂名市| 诸暨市| 保德县| 宁蒗| 湘西| 宜城市| 潜山县| 建昌县| 井研县| 同江市| 黄石市| 凌云县| 平原县| 分宜县| 灌云县| 陆丰市| 苍南县| 西林县| 浏阳市| 延吉市| 富蕴县| 瑞丽市| 玛多县| 白城市| 葫芦岛市| 岢岚县| 屏山县| 太湖县|