1. 程式人生 > >django學習記錄-django-1.5中簡單地自定義自己的使用者模型

django學習記錄-django-1.5中簡單地自定義自己的使用者模型

官方文件

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'] 
is_active:啟用狀態,預設是True

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

admin.py
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)