[英]What is the proper way to add column in user model in 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和migration選項,但是沒有任何效果,因為我對django非常陌生,請幫助我
我正在使用:-Python2.7,Django 1.6,django-allauth 0.15.0
實際發生的問題是,在這種情況下,我創建的字段或列實際上未在數據庫中創建,並且無法運行syncdb,所以最終我得到了答案,我們必須使用South創建架構遷移來創建新表。
python manage.py schemamigration appname --auto
一旦我們按照自己的喜好編寫並測試了此遷移,就可以運行遷移並通過Django管理員驗證其是否達到了我們的預期。
python manage.py migrate
並且還對form.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()
嘗試這樣的事情:
# 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),以查看新類是否與電話號碼和所有其他用戶字段一起出現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.