10

I've created rest APIs using Django-rest-auth, in login, it's returning key and some user info, But I need to add some status like success and message and some other things. Is there any way to override view of django-rest-auth for login?

class TokenSerializer(serializers.ModelSerializer):
    user = UserSerializer(many=False, read_only=True)  # this is add by myself.
    device = DeviceSerializer(many=True, read_only=True)

    class Meta:
        model = TokenModel
        fields = ('key', 'user', 'device',)
JPG
  • 82,442
  • 19
  • 127
  • 206
Kashyap
  • 157
  • 3
  • 15

1 Answers1

16

Create a custom view class and use it

from rest_auth.views import LoginView


class CustomLoginView(LoginView):
    def get_response(self):
        orginal_response = super().get_response()
        mydata = {"message": "some message", "status": "success"}
        orginal_response.data.update(mydata)
        return orginal_response

and change your urls.py as

urlpatterns = [
                  url(r'custom/login/', CustomLoginView.as_view(), name='my_custom_login')

              ] 

now you should use the endpoint /custom/login/ instead of /rest-auth/login

JPG
  • 82,442
  • 19
  • 127
  • 206
  • 1
    Okay, Should I add this view in URL like this ? url(r'^rest-auth/login/$', LoginView.as_view()), and do i need change anything in settings something like we do to use cutom serializer ? Thanks – Kashyap Aug 31 '18 at 08:05
  • Thank you very much. I've one question though if I do the same thing with registration, Do I need to add save function as well. As they've mentioned in their documents?(https://django-rest-auth.readthedocs.io/en/latest/configuration.html) Or It can work with cutsom/registration as well. (I tried that but it's giving me the same response not updated one.) – Kashyap Aug 31 '18 at 10:31
  • 1
    @Kashyap I can't say how to do on registration, because we've to look into the source code to find a better way to do so – JPG Aug 31 '18 at 10:40
  • 1
    @Kashyap So, what I suggest is accept this answer if you got it worked and ask a new question in SO, that may catch more attention that this – JPG Aug 31 '18 at 10:48
  • This is the better way to do it. [Here](https://stackoverflow.com/questions/65158850/how-to-create-custom-login-view-with-django-rest-auth) – Ali Husham Feb 01 '22 at 16:11