歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Django1.5自定義User模型

Django1.5自定義User模型

日期:2017/3/1 9:26:23   编辑:Linux編程

Django1.5自定義用戶profile可謂簡單很多,編寫自己的model類MyUser,MyUser至少要滿足如下要求:

  1. 必須有一個整型的主鍵
  2. 有一個唯一性約束字段,比如username或者email,用來做用戶認證
  3. 提供一種方法以“short”和“long"的形式顯示user,換種說法就是要實現 getfullname和getshortname方法。

一:在project中創建一個account app

django-admin startapp account

二:自定義MyUser

實現自定義User模型最簡單的方式就是繼承AbstractBaseUser,AbstractBaseUser實現了User的核心功能,你只需對一些額外的細節進行實現就可以了。可以看看AbstractBaseUser的源碼:

@python_2_unicode_compatible
class AbstractBaseUser(models.Model):
    password = models.CharField(_('password'), max_length=128)
    last_login = models.DateTimeField(_('last login'), default=timezone.now)

    is_active = True

    REQUIRED_FIELDS = []

    class Meta:
        abstract = True

    def get_username(self):
        "Return the identifying username for this User"
        return getattr(self, self.USERNAME_FIELD)

    def __str__(self):
        return self.get_username()

    def natural_key(self):
        return (self.get_username(),)

    def is_anonymous(self):
        """
        Always returns False. This is a way of comparing User objects to
        anonymous users.
        """
        return False

    def is_authenticated(self):
        """
        Always return True. This is a way to tell if the user has been
        authenticated in templates.
        """
        return True

    def set_password(self, raw_password):
        self.password = make_password(raw_password)

    def check_password(self, raw_password):
        """
        Returns a boolean of whether the raw_password was correct. Handles
        hashing formats behind the scenes.
        """
        def setter(raw_password):
            self.set_password(raw_password)
            self.save(update_fields=["password"])
        return check_password(raw_password, self.password, setter)

    def set_unusable_password(self):
        # Sets a value that will never be a valid hash
        self.password = make_password(None)

    def has_usable_password(self):
        return is_password_usable(self.password)

    def get_full_name(self):
        raise NotImplementedError()

    def get_short_name(self):
        raise NotImplementedError()

AbstractBaseUser只有getfullname和getshortname方法沒有實現了。 接下來我們就通過繼承AbstractBaseUser來自定義User模型叫MyUser:

class MyUser(AbstractBaseUser, PermissionsMixin):
    username = models.CharField('username', max_length=30, unique=True,
                                db_index=True)
    email = models.EmailField('email address',max_length=254, unique=True)
    date_of_birth = models.DateField('date of birth', blank=True, null=True)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    is_staff = models.BooleanField('staff status', default=False,
        help_text='Designates whether the user can log into this admin '
              'site.')
    is_active = models.BooleanField('active', default=True,
        help_text='Designates whether this user should be treated as '
               'active. Unselect this instead of deleting accounts.')

    def get_full_name(self):
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        return self.first_name

    objects = MyUserManager()
USERNAME_FIELD :作為用戶登錄認證用的字段,可以usename,或者email等,但必須是唯一的。

REQUIRED_FIELDS :使用createsuperuser命令創建超級用戶時提示操作者輸入的字段

is_staff :判斷用戶是否可以登錄管理後台

is_active :判斷用戶是否可以正常登錄

三:自定義MyUserManager

同時要為MyUser自定義個一個manager,通過繼承BaseUserManager,提供creat_user和create_superuser方法。

class MyUserManager(BaseUserManager):
    def create_user(self, username, email=None, password=None, **extra_fields):
        now = timezone.now()
        if not email:
            raise ValueError('The given email must be set')
        email = UserManager.normalize_email(email)
        user = self.model(username=username, email=email,
                           is_staff=False, is_active=True, is_superuser=False,
                           last_login=now, **extra_fields)

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, email, password, **extra_fields):
        u = self.create_user(username, email, password, **extra_fields)
        u.is_staff = True
        u.is_active = True
        u.is_superuser = True
        u.save(using=self._db)
        return u

四:指定AUTHUSERMODEL

覆蓋默認的AUTHUSERMODEL,在settings.py文件中增加: AUTHUSERMODEL = 'user.MyUser'

五:注冊MyUser

在account模塊下創建admin.py,添加如下代碼把MyUser模型注冊到admin中:

from django.contrib import admin
from user.models import MyUser
admin.site.register(MyUser)

總結:實現自定義的User模型在Django1.5足夠簡單方便,根據自己需求繼承AbstractBaseUser就可以了。當然如果你想了解更多關於Django 自定義用戶模型相關內容,官方文檔告訴你更多更好的完好

如果你有什麼建議和問題歡迎留言。

Django1.8返回json字符串和接收post的json字符串內容 http://www.linuxidc.com/Linux/2015-07/120226.htm

如何使用 Docker 組件開發 Django 項目? http://www.linuxidc.com/Linux/2015-07/119961.htm

Ubuntu Server 12.04 安裝Nginx+uWSGI+Django環境 http://www.linuxidc.com/Linux/2012-05/60639.htm

Django+Nginx+uWSGI 部署 http://www.linuxidc.com/Linux/2013-02/79862.htm

Django實戰教程 http://www.linuxidc.com/Linux/2013-09/90277.htm

Django Python MySQL Linux 開發環境搭建 http://www.linuxidc.com/Linux/2013-09/90638.htm

Django 的詳細介紹:請點這裡
Django 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved