我有自定義用戶如何在自定義用戶模型中保存來自allauth自定義註冊表單的字段?
# custom_user/models.py
class MyUser(AbstractBaseUser, PermissionsMixin):
USER_ACCOUNT_TYPE_CHOICES = (
(1, _('organization')),
(2, _('personal')),
)
user_account_type = models.IntegerField(_('account type'), choices=USER_ACCOUNT_TYPE_CHOICES)
email = models.EmailField(_('email address'), max_length=255, unique=True)
USERNAME_FIELD = 'email'
class MyUserManager(BaseUserManager):
def _create_user(self, email, password, username=None, **extra_fields):
"""
Creates and saves a User with the given username, email and password.
"""
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
if username:
username = self.model.normalize_username(username)
user = self.model(username=username, email=email, **extra_fields)
else:
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email=None, password=None, username=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, username=username, **extra_fields)
def create_superuser(self, email, password, username=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, username=username, **extra_fields)
在設置有信息要使用的User Model
和在哪裏可以找到更多的領域,我需要在用戶註冊。
# settings.py
ACCOUNT_SIGNUP_FORM_CLASS = 'custom_user.forms.SignupForm'
AUTH_USER_MODEL = 'custom_user.MyUser'
我發現很多不同的方法主題配置allauth's SignupForm
,但沒有人的作品。其中一個方法是如下:
# custom_user/forms.py
from django.forms import ModelForm
from .models import MyUser
class SignupForm(ModelForm):
class Meta:
model = MyUser
fields = ['user_account_type']
def signup(self, request, user):
user.user_account_type = self.cleaned_data['user_account_type']
user.save()
在瀏覽器中我看到兩個選擇(組織\個人)
索取信息 POST
Variable Value
email '[email protected]'
password2 'Test1234'
csrfmiddlewaretoken 'VvrW6PcR8G8OD3fDzunXbtDh4LdYiwzs5xxaYH4xvj'
password1 'Test1234'
user_account_type '1'
username 'Test'
所以allauth看到現場,但無法保存DB中的值。
實際的錯誤是:
IntegrityError at /accounts/signup/
null value in column "user_account_type" violates not-null constraint
是我def signup
是否正確?我還需要配置什麼?
的Django 1.10,allauth v0.26.1
編輯:我發現workaround
def signup(self, request, user):
user_account_type = self.cleaned_data['user_account_type']
MyUser.objects.filter(email=user).update(user_account_type=user_account_type)
但在這種情況下user_account_type
還必須包括null=True, blank=True
什麼應改爲避免這種解決方法並一步保存所有註冊信息(電子郵件,密碼,帳戶類型)?爲什麼allauth
在保存電子郵件和密碼時不能在同一個流程中保存user_account_type
?