django – 修改原生用户表添加自己需要的字段

  • Post author:
  • Post category:其他


1 创建应用 users

python manage.py startapp users

2 修改 users 下 models.py

from django.db import models
#导入需要的类
from django.contrib.auth.models import AbstractUser

# Create your models here.

class UserProfile(AbstractUser):
    #追加字段 头像图片
	header_img = models.ImageField(upload_to="media/%Y-%m", default="media/2020-08/anonymous.jpg", max_length=100, verbose_name="头像");

    #追加字段 生日
	birday = models.DateField(verbose_name="生日", null=True, blank=True);

    #追加字段 是否登陆
	login_status = models.BooleanField(default="False",verbose_name="是否登陆中")
	
	def __str(self):
		return self.username

	class Meta():
		verbose_name = "用户信息"
		verbose_name_plural = verbose_name

		# 邮箱设为唯一键 一个邮箱只对应一个账号
		# unique_together = (("article", "email"),)
		unique_together = (("email"),)

3 修改setting.py

INSTALLED_APPS = [
    'treatment_record',
    'users'
]

AUTH_USER_MODEL  = "users.UserProfile";

4 执行迁移

如果设置了 ImageField字段 会提示需要安装 Pillow包

Cannot use ImageField because Pillow is not installed.

(hulishuju_env) C:\hulishuju>pip install Pillow-7.2.0-cp38-cp38-win_amd64.whl

如果已经migrate过 会提示错误django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency user.0001_initial on database ‘default’.

#删除对应数据库
mysql> drop database django_library;

#重新创建
mysql> create database django_library default character set utf8

5 制作文件并迁移

python manage.py makemigrations
python manage.py migrate



版权声明:本文为wzq29931927原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。