在django-allauth中在用户模型中添加列的正确方法是什么?

时间:2014-07-19 16:15:00

标签: python django python-2.7 django-allauth

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

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和迁移选项,但没有什么可行的,因为我是django的新手,请帮帮我

我正在使用: - Python2.7,Django 1.6,django-allauth 0.15.0

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:-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),看看您的新类是否显示电话号码和所有其他用户字段。