2014-03-12 27 views
2

如果我創建一個CustomUser模型,從django.contrib.auth.models.User繼承,像這樣:Django的 - 擴展`auth.models.User`和usering登錄,註銷

in models.py

class CustomUser(django.contrib.auth.models.User): 
    customfield = TextField() 
    ... 

如果我仍然能夠以正常方式使用 django.contrib.auth.{authenticate, login, logout}?我必須做一些額外的配置更改嗎?我知道這些方法只適用於User對象,但在技術上我的CustomUser是-User

目前,authenticate(username=u, password=p)總是返回None,即使使用有效憑證。

+0

你正在使用哪個版本的django? – mrcrgl

+0

@Marc'Django == 1.6.2',感謝您的幫助 – jaynp

回答

2

由於Django的1.5(正式,但它不爲我工作)和1.6中的「穩定」,有一種功能可以以一種乾淨的方式擴展用戶模型。

起初:

- >拍攝,你只能通過加載用戶模型護理:

from django.contrib.auth import get_user_model 
User = get_user_model() 

- >一旦你已經建立了數據庫,世界上沒有簡單的方法來改變用戶的模式。數據庫關係會中斷,Django/South無法修復它。

- >第三方模塊必須與該新佈局兼容,並將其模型引用到「get_user_model()」。

你必須添加一些代碼爲admin尊重你的新模式: 參見:https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model

覆蓋您需要從AbstractBaseUser繼承模型:

from django.contrib.auth.models import AbstractBaseUser 

class MyUser(AbstractBaseUser): 
    ... 
    date_of_birth = models.DateField() 
    height = models.FloatField() 
    ... 
    REQUIRED_FIELDS = ['date_of_birth', 'height'] 

AbstractBaseUser爲您提供的所有屬性的默認用戶模型。所以,你不必照顧電子郵件,用戶名,名字,姓氏,密碼等 更多信息的有關覆蓋用戶模型:https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.models.CustomUser

在你設置鏈接的新模式:

AUTH_USER_MODEL = 'customauth.MyUser' 

請閱讀整個documentation of customizing the user model,覆蓋默認管理器,管理表單等有一些有趣的提示。請記住,現有項目中的更大更改可能是一個很大的麻煩。

+0

MyUser可以與內置組一起使用還是必須修改。 (即AUTH_USER_MODEL定義足以將它們連接在一起)? – brechmos

+0

是的,只需在您的模型中傳遞PermissionsMixin(在django.contrib.auth.models中找到)此mixin處理模型關係和方法 – mrcrgl