基於 Django1.5自定義user模型

今天看到 http://my.oschina.net/lxcong/blog/145260這篇 blog有感,因此將本身的使用經驗整理出來給你們作一個參考。 python

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'

最後,只須要在視圖裏直接 使用 django

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/")
相關文章
相關標籤/搜索