官方文档
django-1.5之前,要拓展django中现有的用户模型,有两种方式
1. 如果只是想对user模型的行为,如:排序,定制管理器等,可以创建一个proxy model
2. 如果是希望为user添加一些额外的数据,比如:为user添加一个birthday的字段呀,普遍的做法是创建一个称为profile model的模型,与django中现有的用户模型
建立一个一对一关系。
但是在1.5之后,就不推荐上述两种做法了,因为在1.5开始,我们可以直接使用自己的定义的user模型。
首先,要在setting.py里面添加
AUTH_USER_MODEL = 'myapp.MyUser',注意的是,这里是app的名字和我们定义的user类,中间没有models这个东西
当我们需要使用自定义的user类的时候,最好是这样的形式:
class Article(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL)
因为如果你直接是:
class Article(models.Model):
author = models.ForeignKey(MyUser)
一旦你改变了自定义user类,比如MyUser2,则上面那个外键的定义就无效了
自定义user模型,最简单的方式就是继承AbstractBaseUser这个类了,继承这个类之后,必须提供下面的属性:
USERNAME_FIELD:唯一标识的字段。一般是username,也可以是其他的
class MyUser(AbstractBaseUser):
identifier = models.CharField(max_length=40, unique=True, db_index=True)
...
USERNAME_FIELD = 'identifier'
REQUIRED_FIELDS:使用createsuperuser来创建超级用户的时候所需要提供的字段,必须是任意blank=false的字段,不能是外键
class MyUser(AbstractBaseUser):
...
date_of_birth = models.DateField()
height = models.FloatField()
...
REQUIRED_FIELDS = ['date_of_birth', 'height']
get_full_name()
get_short_name()
上面两个方法字面上就是要返回user的全面和简短名,其实随便你。AbstractBaseUser还有其他一些方法,官方文档中都有
定义完自己的user模型后,就需要为这个模型创建一个管理器。如果你自定义的user模型中同样包含有
username, email, is_staff, is_active, is_superuser, last_login,date_joine这些字段,可以直接使用django内置的UserManager。
为自定义的user模型创建的管理器必须继承AbstractBaseUser,我们必须提提供下面两个方法:
create_user(*username_field*, password=None, **other_fields):创建用户
create_superuser(*username_field*, password, **other_fields):创建超级用户
当然,还有其他的方法,也都在官方文档里面
之后,自定义user模型还得重载一些form,包括:UserCreationForm,UserChangeForm。其他的嘛,可以不用重载了
之后还有,自定义权限呀,测试呀,信号呀等等,好长~之后再慢慢看吧~
最后在官方文档中有一个完整的例子,可以照着写
models.py
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):
"""
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=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):
"""
Creates and saves a superuser with the given email, date of
birth and 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):
# 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 __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):
"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
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)