Django rest + React front

Viewed 164

Currently, I am working with a group to try to create a website with a functional Django backend and a React frontend. We are using a user view set

class UserViewset(viewsets.GenericViewSet, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin):
    permissions_classes = (permissions.AllowAny,)
    serializer_class = UserSerializer
    queryset = User.objects.all()

This is where I am stuck, I haven't used viewsets or serializers before and I am at an impasse on where to go from here. I was hoping to get some clarification of how to add in a create/register user plus login and logout functions so that we can start messing with our api. Any help would be appreciated.

1 Answers

For Login you can use the following code in urls.py-:

    from rest_framework.authtoken.views import obtain_auth_token

    urlpatterns=[
    //your urls
    path("api/login/",obtain_auth_token,name="auth_user_login"),]//<-- include this line 
                ]

You can use this endpoint to authenticate using token authentication. For this you need to do some modification in settings.py file

INSTALLED_APPS=[
//Your existing apps
'rest_framework.authtoken'
]

REST_FRAMEWORK={"DEFAULT_AUTHENTICATION_CLASSES":(
                "rest_framework.authentication.TokenAuthentication",
                "rest_framework.authentication.SessionAuthentication"

            ),
}

In react you can send post request to this endpoint with username and password for login. This will send back authentication token which will be used in next requests that needs authentication.

Related