Django Rest Aut - User registration

半城伤御伤魂 提交于 2019-12-24 14:58:59

问题


I´m using Django Rest Auth on Django 1.9 to register new users on system. And I need to execute some extra code in this process to save extra data on another tables.

Anybody knows the best way to do it?


回答1:


Write CustomRegisterSerializer and add it to settings.py file.

    REST_AUTH_REGISTER_SERIALIZERS = {
        "REGISTER_SERIALIZER":"common_app.serializers.CustomRegisterSerializer"
    }

Write save() method of newly created serializer and put some extra executable code.
If your user model have extra fields, you can write your validate_field methods.

For reference you can check rest_auth RegistrationSerializer here https://github.com/Tivix/django-rest-auth/blob/master/rest_auth/registration/serializers.py

I hope this helps.




回答2:


I am agree with @ashish2py 's reply above:

However, want to add an example for custom serializer's save method for other's references.

Steps:

  1. In settings.py file add below line. (assuming your app name is "common_app")

    REST_AUTH_REGISTER_SERIALIZERS = {
        "REGISTER_SERIALIZER":"common_app.serializers.CustomRegisterSerializer"
    }
    
  2. In common_app/serializer.py file add CustomRegisterSerializer class as below (which override save method).

    class CustomRegisterSerializer(RegisterSerializer):
      def save(self, request):
        user = super(CustomRegisterSerializer, self).save(request)
        logger.debug("[GroupProfile-Manager] Manager user registration #{}: {}".format(user.id, user.email))
    
    
        ### YOUR CUSTOM LOGIC GOES HERE ###
    
        group_prof_obj.join(user=user, role='manager')
    
        return user
    


来源:https://stackoverflow.com/questions/36090966/django-rest-aut-user-registration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!