当前位置 : 主页 > 网络编程 > 其它编程 >

Django自定义用户认证

来源:互联网 收集:自由互联 发布时间:2023-07-02
自定义一个用户认证详细参考官方文档:https:docs.djangoproject.comen1.9topicsauthcustomizing#django.contrib.aut 自定义一个用户认证 详细参考官方文档: https://docs.djangoproject.com/en/1.9/topics/auth/customi
自定义一个用户认证详细参考官方文档:https:docs.djangoproject.comen1.9topicsauthcustomizing#django.contrib.aut

自定义一个用户认证

详细参考官方文档:

https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#django.contrib.auth.models.PermissionsMixin.has_perms

一、创建用户的表

UserProfile():存放用户信息的表

UserProfileManager(): 用户创建用户的类方法

1、生成一个单独的Moel文件专门用来存放用户表

#!/usr/bin/env python# _*_coding:utf-8_*_from django.db import modelsfrom django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser)class UserProfileManager(BaseUserManager): def create_user(self, email, name, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user(email, password=password, name=name ) user.is_admin = True user.save(using=self._db) return userclass UserProfile(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) name = models.CharField(max_length=64) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) class Meta: verbose_name = '用户表' verbose_name_plural = '账户表' objects = UserProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their email address return self.email def __str__(self): # __unicode__ on Python 2 return self.email 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_adminuser_models.py

2、在models里面添加自定义的用户表

# _*_coding:utf-8_*_from django.db import modelsfrom collect_app.user_models import UserProfile

3、在settings里面指定自定义表的位置,django会默认去models文件里去找相应的表 (app名+表名)

AUTH_USER_MODEL = 'collect_app.UserProfile'

  

此时,在用Manage.py创建用户时,就是自定义的创建过程

二、在Django Admin里面显示自定义的用户表

要把自定义的用户表在Django admin里面显示,需要稍加修改并注册到admin里

1、创建user_admin.py用来重写admin。

2、创建用户显示的UserAdmin类方法,并将其中的字段与自定义用户表的字段对应

3、创建更改用户和创建用户的类方法

#!/usr/bin/env python# _*_coding:utf-8_*_from django import formsfrom django.contrib import adminfrom django.contrib.auth.models import Groupfrom django.contrib.auth.admin import UserAdmin as BaseUserAdminfrom django.contrib.auth.forms import ReadOnlyPasswordHashFieldfrom collect_app.models import UserProfile # 导入自定义的用户表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: # 将其关联到UserProfile表 model = UserProfile fields = ('email', 'name') 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(UserCreationForm, self).save(commit=False) # 继承父类的save方法 并重写 user.set_password(self.cleaned_data["password1"]) if commit: user.save() # 保存创建的密码 return userclass 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 = UserProfile # 将其关联到UserProfile表 fields = ('email', 'password', 'name', 'is_active', 'is_admin') def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not have access to the initial value return self.initial["password"]class UserAdmin(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 = ('email', 'name', 'is_admin') # 显示的字段 list_filter = ('is_admin',) fieldsets = ( # 分行显示 (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('name',)}), ('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': ('email', 'name', 'password1', 'password2')} # 创建用户时显示的字段 ), ) search_fields = ('email',) # 按email搜索 ordering = ('email',) filter_horizontal = ()# Now register the new UserAdmin...# admin.site.register(UserProfile, UserAdmin)# ... and, since we're not using Django's built-in permissions,# unregister the Group model from admin.admin.site.unregister(Group) # 不显示Groupuser_admin.py

4、将自定义UserAdmin的方法注册到admin里面

from user_admin import UserAdminadmin.site.register(models.UserProfile, UserAdmin) # 将自定义的Admin注册到自定义的用户表中。

至此,再次登录django admin时,用户的信息就是我们自定义的信息。包括修改和创建用户时,都是我们自定义的内容。

上一篇:阿里云centos系统yum源错误解决方法
下一篇:没有了
网友评论