django繼承user類來定制自己的user類


Django開發bug及問題記錄

開發環境

python:3.6.4
Django:1.11
IDE:pycharm
OS:windows10

自己新增的userprofile表去覆蓋原有的auth_user表,遇到的錯誤:

1

Django1.11 在重寫用戶模型時報錯:

AttributeError: type object ‘UserProfile’ has no attribute ‘USERNAME_FIELD’ models.py

新建用戶模型UserProfile繼承自AbstractBaseUser

debug時報錯: AttributeError: type object 'UserProfile' has no attribute 'USERNAME_FIELD'

在模型中新增兩行代碼,即可解決

identifier = models.CharField(max_length=40, unique=True)
USERNAME_FIELD = 'identifier'

補充:事實證明, 網上的方法靠不住.用這個方式, 后面會在添加用戶的時候,把username替換為identifier,創建用戶提示username缺失.所以

identifier = models.CharField(max_length=40, unique=True)

這一行刪除

USERNAME_FIELD = 'identifier'

這一行改成

USERNAME_FIELD = "username"

2

Django在執行python manage.py makemigrations的時候提示異常:

django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency user.0001_initial on database 'default'

原因:Django中有一個原生的User模型類,admin的模型依賴這個模型類,由於前面一個應用中的模型類User繼承了AbstractUser類,所以提示這個錯誤。

解決方案:

刪除數據庫中 除了auth_user的其他表,然后重新來一次。直接刪除數據庫,再新建最快了,不然刪除一堆的有外鍵的,會分成好幾次執行.

參考

3

django中使用了自定義的UserProfile類,去覆蓋django自己自帶的auth_user類,發現不論怎么樣,生成的userprofile表,總是只有前三個字段是繼承auth_user表來的,后來才發現UserProfile類繼承的不是AbstractUser類,而是繼承了AbstractBaseUser類.前者是給用來繼承所有auth_user類的的,后者是當auth_user中的字段,用戶幾乎都不要時才會去繼承的.

4

django報

1050, "Table 'django_content_type' already exists"

刪除數據庫,重新命名同名數據庫.....


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM