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

前端 未结 2 882
时光说笑
时光说笑 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:26

    It seems like django-allauth doesn't allow saving custom fields by default:

    (ref: https://github.com/pennersr/django-allauth/blob/master/allauth/account/adapter.py#L227)

    To go around it, simply assign the custom field values before doing user.save()

    self.cleaned_data = self.get_cleaned_data()
    adapter.save_user(request, user, self)
    setup_user_email(request, user, [])
    
    user.address = self.cleaned_data.get('address')
    user.user_type = self.cleaned_data.get('user_type')
    
    user.save()
    return user
    

    That was a dirty fix. A cleaner way would be to override the allauth adapter to support your custom fields.

    0 讨论(0)
  • 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'
    
    0 讨论(0)
提交回复
热议问题