如何在django-allauth的用户模型中添加列?

1 投票
2 回答
772 浏览
提问于 2025-04-18 13:57

下面是我尝试在用户模型中添加一个电话号码列的内容:

from django.contrib.auth.models import AbstractUser

# models.py

# Import the basic Django ORM models library
from django.db import models

from django.utils.translation import ugettext_lazy as _


# Subclass AbstractUser
class User(AbstractUser):
    phonenumber = models.CharField(max_length=15)

    def __unicode__(self):
        return self.username

# forms.py

from django import forms

from .models import User
from django.contrib.auth import get_user_model

class UserForm(forms.Form):

    class Meta:
        # Set this form to use the User model.
        model = get_user_model

        # Constrain the UserForm to just these fields.
        fields = ("first_name", "last_name", "password1", "password2", "phonenumber")

    def save(self, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.password1 = self.cleaned_data['password1']
        user.password2 = self.cleaned_data['password2']
        user.phonenumber = self.cleaned_data['phonenumber']
        user.save()

# settings.py

AUTH_USER_MODEL = "users.User"
ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.UserForm'

但是在这个修改后,出现了一个错误:OperationalError: (1054, "未知列 'users_user.phonenumber' 在 '字段列表' 中")

我已经使用了syncdb和migrate选项,但都没有效果。因为我对django还很陌生,请大家帮帮我。

我使用的是:-
Python2.7,Django 1.6,django-allauth 0.15.0

2 个回答

-1

试试这样做:

# models.py

# Subclass AbstractUser
class CustomUser(AbstractUser):
    phonenumber = models.CharField(max_length=15)

    def __unicode__(self):
        return self.username

# settings.py

AUTH_USER_MODEL = 'myapp.CustomUser'

这里的意思是,你应该使用你的子类,而不是原来的用户类。我觉得你可能还需要在你的表单代码里做一些修改,不过先测试一下这个(然后运行 manage.py syncdb),看看你的新类是否能显示出电话号码和其他用户信息。

0

其实问题出在我创建的字段或列并没有在数据库中真正创建,而运行syncdb也没有用。最后我找到了解决办法,我们需要使用South来创建数据库结构的迁移,以便创建新的表。

python manage.py schemamigration appname --auto

一旦我们写好了这个迁移并测试得满意,就可以运行迁移,并通过Django的管理后台确认它是否按我们预期的那样工作。

python manage.py migrate

同时,我在forms.py文件中也做了一些修改。

# forms.py

class UserForm(ModelForm):

    class Meta:
        # Set this form to use the User model.
        model = User

        # Constrain the UserForm to just these fields.
        fields = ("username", "email", "phonenumber")

    def save(self, user):
        user.username = self.cleaned_data['username']
        user.email = self.cleaned_data['email']
        user.phonenumber = self.cleaned_data['phonenumber']
        user.save()

撰写回答