django使用AbstractUser扩展用户报错,makemigrations报错问题,admin报错问题

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/u013251692/article/details/102749881
  • 我自己是account应用下创建扩展用户模型的model叫UserProfile
class UserProfile(AbstractUser):
    date_of_birth = models.DateField(blank=True, null=True)
    photo = models.ImageField(upload_to='user/%Y/%m/', blank=True)
    phone = models.CharField(max_length=11, verbose_name="手机号码", default="")
    address = models.CharField(max_length=100, verbose_name='地址')

    def __str__(self):
        return "Profile for user {}".format(self.username)

虽然自己的UserProfile里面没有username字段,但是这个UserProfile是继承自User的,可以直接使用User的字段,User里面常用的字段也就是usernmae,email,password了,可以直接使用

类似test=UserProfile.objects.first().username是可以直接用的


  • 在总项目文件的setting.py下添加
AUTH_USER_MODEL = 'account.UserProfile'

account是你的应用名,UserProfile是你的model名


  • 在account应用下注册到管理后台admin.py
from django.contrib import admin
from .models import UserProfile
from django.contrib.auth.models import User


@admin.register(UserProfile)
class ProfileAdmin(admin.ModelAdmin):
    list_display = ['username', 'date_of_birth', 'photo', 'phone', 'email', 'address']

把username放在前面方便一点,如果不写username可能会报错,提示你没有选择用户什么的


如果你已经有了别的应用才扩展用户信息的话可能还会报错,会提示你别的app下的各种model或者表单会因为使用了User而报错,全都改成UserProfile就好了


由于我是在创建好多应用之后才改的model,然后迁移数据migrate一直报错(网上查了一下,是因为之前一直使用的默认User,产生了很多依赖,后期有数据后在扩展User模型会因为依赖问题没有办法迁移,除非自己手动一个个更改),由于我还是练习阶段,解决方法就简单粗暴了一点,直接删库,然后把每个应用下的migrations的文件夹内除了__init__.py文件之外的全删除掉,然后再次迁移就好了

猜你喜欢

转载自blog.csdn.net/u013251692/article/details/102749881