django-rest-auth custom registration fails to save extra fields

前端 未结 2 885
时光说笑
时光说笑 2020-12-15 13:17

I am using DRF and for login/registration I am using Django-rest-auth.

  1. I have customized User model to have extra fields
  2. I have custom registration s
2条回答
  •  无人及你
    2020-12-15 13:38

    To override the default adapter and save the custom fields try the following

    Create an adapters.py file in your app root folder and paste the code below

    from allauth.account.adapter import DefaultAccountAdapter
    
    
    class CustomUserAccountAdapter(DefaultAccountAdapter):
    
        def save_user(self, request, user, form, commit=True):
            """
            Saves a new `User` instance using information provided in the
            signup form.
            """
            from allauth.account.utils import user_field
    
            user = super().save_user(request, user, form, False)
            user_field(user, 'address', request.data.get('address', ''))
            user_field(user, 'first_name', request.data.get('first_name', ''))
            user_field(user, 'last_name', request.data.get('last_name', ''))
            user_field(user, 'user_type', request.data.get('user_type', ''))
            user.save()
            return user
    

    Lastly set the settings configuration to use your custom adapter by adding this line in the settings.py file

    ACCOUNT_ADAPTER = 'users.adapters.CustomUserAccountAdapter'
    

提交回复
热议问题