网站建设资讯

NEWS

网站建设资讯

Django中怎么自定义用户模块

这篇文章将为大家详细讲解有关Django 中怎么自定义用户模块,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

十多年的斗门网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。营销型网站建设的优势是能够根据用户设备显示端的尺寸不同,自动调整斗门建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。创新互联从事“斗门网站设计”,“斗门网站推广”以来,每个客户项目都认真落实执行。

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 中怎么自定义用户模块就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


分享文章:Django中怎么自定义用户模块
转载注明:http://cdweb.net/article/jjjegc.html