问题
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:
In settings.py file add below line. (assuming your app name is "common_app")
REST_AUTH_REGISTER_SERIALIZERS = { "REGISTER_SERIALIZER":"common_app.serializers.CustomRegisterSerializer" }
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