今天看到 http://my.oschina.net/lxcong/blog/145260这篇 blog有感,所以将自己的使用经验整理出来给大家做一个参考。
Django自带的user模型在权限粒度切分,session控制,用户认证方面整合的很好,通常我都用它来做项目的用户模型,但是在Django1.5之前,user模型只能用系统自带的字段,不能对字段进行扩展,只能添加一个类似于profile的模型和user进行关联,用user来做权限控制,用profile存储做用户相关资料.这个办法我一直从Django 0.96版本沿用到Django 1.4.
直到Django1.5允许自定义user模型之后,我可以不再蛋疼的使用profile模型来和user进行关联了.而是直接对user模型进行扩展.
首先介绍两个类,BaseUserManager, AbstractBaseUser. 来自于django.contrib.auth.models,有兴趣的朋友可以去看看他们的继承关系和实现.
BaseUserManager 继承自 models.Manager接口,我们需要重写其中的两个方法:
def create_user(self):
这个方法用于在业务代码中直接创建user模型对象
def create_superuser(self):
这个方法用户在执行manage.py syncdb 同步数据库时创建超级管理员
以下是这两个方法的完整示例,我仅贴出符合我的业务需求的例子,可以根据自己的不同情况进行修改
#通行证管理类
class PassportManager(BaseUserManager):
#创建user
def create_user(self, email, username, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email = PassportManager.normalize_email(email),
username = username,
uuid = str(uuid.uuid1()),
)
user.set_password(password)
user.uuid = str(uuid.uuid1())
user.save(using=self._db)
return user
#创建超级管理员
def create_superuser(self, email,username, password):
user = self.create_user(email,
username = username,
password = password,
)
user.uuid = str(uuid.uuid1())
user.is_staff = True
user.is_active = True
user.is_admin = True#通行证
AbstractBaseUser类继承自models.Model,并且实现了一堆对user模型操作的实用方法.get_username,is_anonymous,is_authenticated等等.我们可以继承AbstractBaseUser类并进行具体的user模型定义.
class passport(AbstractBaseUser):
uuid = models.CharField(max_length=36,unique=True, db_index=True)
username = models.CharField(max_length=40, unique=True, db_index=True)
email = models.EmailField(max_length=254)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
address = models.CharField(max_length=140,blank=True, null=True)
birth = models.DateField(blank=True, null=True)
id_card = models.CharField(max_length=20,blank=True, null=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
objects = PassportManager()
class Meta:
app_label = 'passport'
user.save(using=self._db)
return user
以下是我的model.py全部代码
#! /usr/bin/env python
#coding=utf-8
import uuid
from django.conf import settings
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
#管理类
class PassportManager(BaseUserManager):
#创建user
def create_user(self, email, username, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email = PassportManager.normalize_email(email),
username = username,
uuid = str(uuid.uuid1()),
)
user.set_password(password)
user.uuid = str(uuid.uuid1())
user.save(using=self._db)
return user
#创建超级管理员
def create_superuser(self, email,username, password):
user = self.create_user(email,
username = username,
password = password,
)
user.uuid = str(uuid.uuid1())
user.is_staff = True
user.is_active = True
user.is_admin = True
user.save(using=self._db)
return user
#通行证
class passport(AbstractBaseUser):
uuid = models.CharField(max_length=36,unique=True, db_index=True)
username = models.CharField(max_length=40, unique=True, db_index=True)
email = models.EmailField(max_length=254)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
address = models.CharField(max_length=140,blank=True, null=True)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
objects = PassportManager()
class Meta:
app_label = 'passport'
最后,只需要在视图里直接 使用
passport.objects.create_user(email,username,password)
就可以创建自定义的user模型对象了
简单的登录验证:
passportObj = auth.authenticate(username = username, password = password)
#如果验证成功
if passportObj is not None:
#登记登录信息
auth.login(request, passportObj)
#返回主页
return HttpResponseRedirect("/passport/")