Search code examples
djangodjango-rest-frameworkdjango-rest-auth

How do i extend the Register method in django-rest-auth in django?


Currently, when my user registers and there is an error, I get the following message back:

status 400
{"username":["This field is required."],"email":["A user is already registered with this e-mail address."],"__all__":["You must type the same password each time."]}

This is for my mobile application and I would like a consistent message when the error is returned (not field specific like 'username', 'email'). For example,

status 400
{"error_message":"username - This field is required. email - A user is already registered with this e-mail address. __all__ - You must type the same password each time."}

Is there anyway I can extend the registration/views/Register class?


Solution

  • You need to override the RegisterView.get_response_with_errors method.

    class MyRegisterView(RegisterView):
        def get_response_with_errors(self):
            errors = my_magic_func(self.form.errors)
            return Response(errors, status=status.HTTP_400_BAD_REQUEST)
    

    Where my_magic_func will do the trick of customizing error message based on the error dict. Then hook up the custom view into your urls:

    url(r'^rest-auth/registration/$', MyRegisterView.as_view(), name='rest_register'),
    

    remember to add it before any rest-auth related urls.