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

前端 未结 1 1343
长发绾君心
长发绾君心 2021-01-01 02:40

I\'m trying to integrate django-allauth with a custom user model (subclassed AbstractUser, but when I test the signup form I get an integrity error due to field (date_of_bir

1条回答
  •  鱼传尺愫
    2021-01-01 03:09

    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
    

    0 讨论(0)
提交回复
热议问题