自定义一个用户认证

详细参考官方文档:

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 models
from 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 user class 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_admin

user_models.py

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

# _*_coding:utf-8_*_

from django.db import models
from 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 forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField from 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 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 = 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) # 不显示Group

user_admin.py

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

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

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

Django自定义用户认证的更多相关文章

  1. CMDB资产管理系统开发【day25】:Django 自定义用户认证

    官方文档:https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#substituting-a-custom-user-mode ...

  2. Django自定义用户认证系统之自定义用户模型

    参考文档:http://python.usyiyi.cn/django/topics/auth/customizing.html Django 自带的认证系统足够应付大多数情况,但你或许不打算使用现成 ...

  3. Django自定义用户认证系统Customizing authentication

    扩展已有的用户模型Extending the existing User model 有两种方法来扩展默认的User Model而不用重写自己的模型.如果你不需要改变存储在数据库中的字段,而只是需要改 ...

  4. 使用django实现自定义用户认证

    参考资料:https://docs.djangoproject.com/en/1.10/topics/auth/customizing/    直接拉到最后看栗子啦 django自定义用户认证(使用自 ...

  5. 自定义用户认证(继承django的)

    1.在app下创建一个自己用户认证文件,文件名随意,记得为.py文件 2.编辑该userauth.py文件 #!/usr/bin/env python #coding:utf-8 from djang ...

  6. python 全栈开发,Day79(Django的用户认证组件,分页器)

    一.Django的用户认证组件 用户认证 auth模块 在进行用户登陆验证的时候,如果是自己写代码,就必须要先查询数据库,看用户输入的用户名是否存在于数据库中: 如果用户存在于数据库中,然后再验证用户 ...

  7. 深入一下Django的用户认证和cache

    深入一下Django的用户认证和cache 用户认证 首先明白一个概念,http协议是无状态的,也就是每一次交互都是独立的,那如何让服务器和客户端进行有状态的交互呢,现在较为常见的方法就是让客户端在发 ...

  8. COOKIE与SESSION、Django的用户认证、From表单

    一.COOKIE 与 SESSION 1.简介 1.cookie不属于http协议范围,由于http协议无法保持状态,但实际情况,我们却又需要“保持状态”,因此cookie就是在这样一个场景下诞生. ...

  9. Django--分页器(paginator)、Django的用户认证、Django的FORM表单

    分页器(paginator) >>> from django.core.paginator import Paginator >>> objects = ['joh ...

随机推荐

  1. zTree的getChangeCheckedNodes()使用

    zTree的getChangeCheckedNodes()方法用于获取输入框勾选状态被改变的节点集合.如果需要获取每次操作后全部被改变勾选状态的节点数据,请在每次勾选操作后,遍历所有被改变勾选状态的节 ...

  2. 数据库创建&数据表创建

    --第2_1题创建数据库 create database Student201038897041 on primary (name='student1', filename='F:\coures\SQ ...

  3. jquery 中fadeIn,fadeOut动画

    我们在做首页banner图片播放的时候会使用fadeIn,fadeOut动画,这里需要注意的是: fadeIn作用相当于:display:list-item;opcity逐渐变为1 fadeOut作用 ...

  4. IT新人养成与蘑菇理论

    (一)来源及定义    “蘑菇定律”最早是在上世纪70年代一批年轻的电脑程序员编写的.当时,美国一批电脑程序员意外发现,一批刚从学校毕业的新人参加了工作,这些人很难适应工作环境.在这种情况下,这些电脑 ...

  5. 1500: [NOI2005]维修数列

    Description Input 输入的第1 行包含两个数N 和M(M ≤20 000),N 表示初始时数列中数的个数,M表示要进行的操作数目.第2行包含N个数字,描述初始时的数列.以下M行,每行一 ...

  6. android 布局如何支持多种不同屏幕尺寸

    android 布局如何支持多种不同屏幕尺寸 --关于dp.layout-xxx.drawable-xxx作用的小结 转载自:http://blog.csdn.net/vincent_blog/art ...

  7. Aircrack-ng官方文档翻译[中英对照]---Airdecap-ng

    Aircrack-ng官方文档翻译---Airdecap-ng   Description[简介] With airdecap-ng you can decrypt WEP/WPA/WPA2 capt ...

  8. Hibernate一对一双向关联(外键)

    网站上各种搜索,都是一些清晰或者不清晰的例子,但是用下来一是确实不给力,二是完全不知道所以然. 后来终于在书中查到了就在这里记一下. 首先要说明,这里只解释双向一对一只有一个表里面有外键的情况. 就以 ...

  9. python中enumerate的使用

    在python的应用中,当我们使用一个数组或者列表的时候既要遍历索引又要遍历元素的时候通常的做法是这样的: >>> lsi = [1,2,3,4,5,6,7,8,9] >> ...

  10. 两种方法,获取磁盘剩余空间--PYTHON

    import ctypes import os import platform import sys def get_free_space_mb(folder): """ ...