Django 重写用户模型时遇到的问题
新建一个app叫users
里面写我们需要的类(users/models)
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
nick_name = models.CharField(verbose_name='昵称',max_length=64, default='')
phone = models.CharField(verbose_name='手机号码',max_length=15,default='')
class Meta:
verbose_name = '用户信息'
verbose_name_plural = verbose_name
在全局settings.py里加上
AUTH_USER_MODEL = 'users.User'
当报如下错误时:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "D:\Python36\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "D:\Python36\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "D:\Python36\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "D:\Python36\lib\site-packages\django\apps\registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "D:\Python36\lib\site-packages\django\apps\config.py", line 90, in create
module = import_module(entry)
File "D:\Python36\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'users'
这个错误主要是路径找不到引起的,只需在settings文件夹中添加app文件路径即可
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
然后再运行:
D:\Python\Django\my_admin>python manage.py makemigrations
Migrations for 'users':
apps\users\migrations\0001_initial.py
- Create model User
完美!