较长 正式 为用户 标识符 。 一个 常见 的 解释 将是 全名 的用户名 , 但它可以是 任何 字符串,用于标识 用户 。
一个简短 的,非正式的 为用户 标识符 。 一个 常见 的 解释 将是第一个 用户的名称 , 但它可以是 任何 字符串,用于标识 用户在 一种非正式的方式 。 它 也可能返回 相同的值
返回的字段值由USERNAME_FIELD提名。
is_anonymous()
始终返回false。
这是的方式分化从AnonymousUser对象。
一般来说,你应该更喜欢使用is_authenticated()这个方法。
is_authenticated()
总是返回true 。
这是一种方式来告诉,如果用户已经通过验证。
这并不意味着任何权限,不检查,如果用户是活跃的 - 它只是表明用户提供了一个有效的用户名和密码。
set_password(raw_password)
给定的原始字符串,用户的密码设置的口令散列照顾。
是否不保存AbstractBaseUser的对象。
check_password(raw_password)
返回True ,如果给定的字符串是正确的用户的密码。
(这需要照顾的口令散列作比较)
set_unusable_password()
标志着用户没有设置密码。
这是不一样的,作为具有一个空字符串输入密码。
check_password()此用户将永远不会返回True。
是否不保存AbstractBaseUser的对象。
您可能需要这一点,如果您的应用程序的身份验证发生对现有的外部源,如LDAP目录。
has_usable_password()
返回false如果set_unusable_password()被称为此用户。
你也应该 定义一个自定义 的 用户 模式 的 经理 。 如果 您 的 用户 模型 定义 的用户名 , 电子邮件 , is_staff , is_active is_superuser last_login 和 date_joined 领域 Django的 默认 用户 一样 , 可以 只 安装 Django 的 的UserManager 然而, 如果 你 的 用户 模型 定义 不同的领域 , 你 必须 定义一个 自定义 管理器 , 扩展 BaseUserManager 提供 两个额外 的 方法 :
class models. CustomUserManager
create_user (*username_field*, password=None, **other_fields)
create_user()的原型应该接受username字段,以及所有必需的字段作为参数。例如,如果您的用户模型使用电子邮件作为用户名“字段中,有DATE_OF_BIRTH作为必填字段,然后create_user应定义为:
def create_user(self, email, date_of_birth, password=None): # create user here ...
create_superuser
(
*
username_field
*
,密码
,**
other_fields
)
的原型
create_superuser
(
)
应该接受
username字段
,以及所有
需要
的
字段
作为参数
。
例如,
如果
您
的
用户
模型
使用电子邮件
作为用户名
“
字段
中
,
有
DATE_OF_BIRTH
作为
必填字段
,
然后
create_superuser
应
定义为
:
def create_superuser(self, email, date_of_birth, password): # create superuser here ...
如果你 完全满意 Django的 用户 模型 , 只是想和你 添加 一些额外的 配置 文件 信息 , 你 可以简单地 的 子 类 django.contrib.auth.models.AbstractUser 和 添加自定义 的 配置文件字段 。 这个类提供了 默认的用户 作为 一个抽象的 模型 全面实施 。
自 定义 用户和 内置的 验证 表格
正如你可能
想到,
内置
Django的
表单和视图
使
用户模型
的
某些假设
,
他们正在与
。
如果您的用户
模型不
遵循相同
的
假设
,它
可能
有必要
定义一个
替换
的形式
,
并
在
作为
配置
的auth
视图
的
一部分
,
通过
这种形式
。
UserCreationForm
取决于
用户
模型
。
必须重新
写
任何用户自定义
模式
。
UserChangeForm
取决于
用户
模型
。
必须重新
写
任何用户自定义
模式
。
AuthenticationForm
工程
与
的任何子类
AbstractBaseUser
,
将
适应
使用该字段
定义
在
USERNAME_FIELD
。
PasswordResetForm
假设
用户模型
有一个整数
的
主键
,
有一个字段
名为email
,
可以用来
识别用户
,
一个布尔字段
名为
is_active
防止
无效
用户
密码重置
的
。
SetPasswordForm
工程
与
任何
AbstractBaseUser
子类
PasswordChangeForm
工程
与
任何
AbstractBaseUser
子类
AdminPasswordChangeForm
工程
与
任何
AbstractBaseUser
子类
可以很容易地 到 自己的 用户 类 包括 Django的 许可 框架 , Django提供 PermissionsMixin 的 。 这是一个抽象 的 模型 , 可以包括在 用户 模式 的类层次结构 , 给你所有 的方法和 必要 支持 Django的 权限 , 模型 数据库字段 。
PermissionsMixin提供了以下的方法和属性:
类models.PermissionsMixin
is_superuser
布尔值。
指定该用户拥有所有权限不明确分配。
get_group_permissions ( OBJ无)
该用户具有权限的字符串返回一组,通过他/她的团队。
如果obj是通过这个特定的对象,只返回该组的权限。
get_all_permissions ( OBJ无)
该用户具有的权限字符串返回一组,通过组和用户权限。
如果obj过去了,只返回这个特定对象的权限。
has_perm (烫发, OBJ =无)
.
如果obj传递,这种方法不会检查权限模型,但这个特定的对象。
has_perms ( perm_list , OBJ =无)
.
如果obj传递,这种方法不会检查模型的权限,但对特定对象进行。
has_module_perms ( PACKAGE_NAME)
返回True ,如果用户有权限在给定的包( Django应用程序标签) 。
如果用户是无效的,此方法将始终返回False。
from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ 创建并保存一个用户给定的电子邮件,日期
出生和密码。 """ if not email: raise ValueError('Users must have an email address') user = self.model( email=MyUserManager.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password): """ 创建并保存一个具有超级用户给定的电子邮件,日期
出生和密码。 """ user = self.create_user(email, password=password, date_of_birth=date_of_birth ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, db_index=True, ) date_of_birth = models.DateField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def get_full_name(self): #用户确定他们的电子邮件地址 return self.email def get_short_name(self): #用户确定他们的电子邮件地址 return self.email def __unicode__(self): 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): "“用户是否有一个具体的权限吗?”
#最简单的可能的答案是:是的,总是
return True @property def is_staff(self):
“是用户工作人员的一员吗?”
#最简单的可能的答案:所有管理员的工作人员
return self.is_admin
from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from customauth.models import MyUser 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: model = MyUser fields = ('email', 'date_of_birth') 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) 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 = MyUser 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 MyUserAdmin(UserAdmin): # 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', 'date_of_birth', 'is_admin') list_filter = ('is_admin',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('date_of_birth',)}), ('Permissions', {'fields': ('is_admin',)}), ('Important dates', {'fields': ('last_login',)}), ) # 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', 'date_of_birth', 'password1', 'password2')} ), ) search_fields = ('email',) ordering = ('email',) filter_horizontal = () # Now register the new UserAdmin... admin.site.register(MyUser, MyUserAdmin) # ... and, since we're not using Django's builtin permissions, # unregister the Group model from admin. admin.site.unregister(Group)