尝试在Django中向用户添加自定义字段

时间:2017-10-25 13:56:57

标签: python django

我对django来说相当新,直到这个时候才开始。

我试图添加字段'地址'和' phone_number'对用户(基本上创建自定义用户),但我一直得到这样的错误......

    $('.side-scroll').each(function() {
    c[n] = st - (f[n]);
    setScroll(c[n], '#cat' + n);
    n++;
    if(n == ss ){n = 0;}
});

这是模型

File "C:\Users\will5\Desktop\City\city_info\forms.py", line 5, in <module>
class UserForm(forms.ModelForm):
File "C:\Users\will5\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\django\forms\models.py", line 257, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (phone_number, address) 
specified for User

这是我的表格

...
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    phone_number = models.IntegerField(default=0)
    address = models.CharField(max_length=150)
...

我还读到,为了解决这个问题,我必须通过创建自定义用户并迁移来重启我的项目,我不想这样做。

1 个答案:

答案 0 :(得分:1)

问题是您仍在导入内置用户模型

您可以通过替换

来解决此问题
from django.contrib.auth.models import User

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

这假设您已在设置中设置AUTH_USER_MODEL = 'yourapp.User'

正如您在文档中看到的那样,在项目启动后切换到自定义用户模型非常困难,但这并不是一个简单的解决方案。如果您无法重新启动项目,也许您可​​以使用Profile创建OneToOneField模型,而不是默认User