关于“User.add_to_class”的错误,扩展用户时出现问题,不知为何

1 投票
1 回答
1047 浏览
提问于 2025-04-15 14:08

在我的models.py文件中,我使用这些代码来扩展两个字段:

User.add_to_class('bio', models.TextField(blank=True))
User.add_to_class('about', models.TextField(blank=True))

但是当我创建一个用户的时候:

user = User.objects.create_user(username=self.cleaned_data['username'], \
            email=self.cleaned_data['email'],password=self.cleaned_data['password1'])

出现了这样的错误:

ProgrammingError at /account/register/
(1110, "Column 'about' specified twice")

Request Method: POST 
Request URL: http://127.0.0.1:8000/account/register/ 
Exception Type: ProgrammingError 
Exception Value: (1110, "Column 'about' specified twice") 

我查看了Django生成的SQL语句,发现它非常奇怪:

'INSERT INTO `auth_user` (`username`, `first_name`, `last_name`, `email`, `password`, `is_staff`, `is_active`, `is_superuser`, `last_login`, `date_joined`, `about`,'bio','about','bio') VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'

关于'about'和'bio'这两个字段有两个。但是在MySQL表中却只有一个'about'和'bio'。

另外,我不知道在什么情况下models.py会被运行两次。

我不知道为什么。请帮帮我!

1 个回答

3

这不是存储额外用户信息的好方法,原因有很多,正如James Bennett在链接的讨论中提到的那样。你遇到奇怪的SQL输出并且很难调试,这一点也不奇怪。为了让自己更轻松,建议你使用一个相关的个人资料模型来处理这些信息。

撰写回答