Search code examples
djangodjango-authenticationdjango-login

How do you use Django Login function properly


What I understand so far is that when you're using regular Django you import and use AuthenticationForm and you put the request.POST there and it will retrieve the user you're looking for. But in this case I'm using DRF and some third party authentication system that retrieve the user for me. so in order to test the login function I made this dummy code to test it:

@api_view(["GET"])
def login_view(request):

    if request.method == "GET":

        #actuall users that exist
        user =     {  
        "id": 1,
        "email": "test@gmail.com",
        "name": "melly",
        "date_joined": "2021-07-09T11:33:44.440889Z"
        }

        login(request, user)


    return Response('test')

and it gave me this error enter image description here

Can someone explain to me about this error and why is this happening, thank you!


Solution

  • According to the docs, the login function takes an HttpRequest object and a User object (not a dict), so you dummy code should be probably be something like that :

    user, has_been_created = User.objects.get_or_create(email=test@gmail.com, ...).

    But please note that the REST API are supposed to be stateless, so you should probably avoid to use the login (based on Django's sessions) and returns a token to your user instead.

    This is called token authentication and you can find docs for DRF here.