django-allauth: custom user generates IntegrityError at /accounts/signup/ (custom fields are nulled or lost)

て烟熏妆下的殇ゞ 提交于 2019-11-30 15:11:21

The answer -- which I'm still figuring out -- seems to be that if you are saving a model that contains field types that allauth.account.adapter.DefaultAccountAdapter doesn't handle correctly (e.g. any field that lacks a __getitem__ attribute, like models.DateField) it is necessary to implement a custom adapter somewhat like below.

note: your subclassed abstract user model is the user that's passed in, so the best practice is to use the form data directly like user.email = data.get('email') rather than using the allauth internal methods used in the DefaultAccountAdapter class

userdata/adapter.py

class AccountAdapter(DefaultAccountAdapter):
    def save_user(self, request, user, form, commit=False):
        data = form.cleaned_data
        user.email = data.get('email')
        user.username = data.get('username')
        # all your custom fields
        user.date_of_birth = data.get('date_of_birth')
        user.gender = data.get('gender')
        if 'password1' in data:
            user.set_password(data["password1"])
        else:
            user.set_unusable_password()
        self.populate_username(request, user)
        if commit:
            user.save()
        return user
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!