What is the proper way to logout the user via class-based view using Django Token Authentication?

HI,

I have my login view working perfectly, and I think the logout view should work properly as well, but everytime I click on the button to logout user, it gives error AonymousUser object has not attribute 'auth_token'.

My views.py is below:

class LoginAPIHTML(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'accounts/login.html'

    def get(self, request):        
        serializer = LoginSerializer()
        return Response({'serializer': serializer})

    def post(self, request):
        serializer = LoginSerializer(data=request.data)
        if not serializer.is_valid():
            return Response({'serializer': serializer})
        
        user = authenticate(request, username=request.data['email'], password=request.data['password'])
        
        if user:
            login(request, user)
            return redirect('user')

        else:
            return redirect('login')

class LogoutAPIHTML(APIView):
    def get(self, request):
        request.user.auth_token.delete()
        logout(request)
        return redirect('login')

and the template from where I click the logout button is below:

<body>
        <h1>Use Details</h1>

        {% if request.user.is_authenticated %}
        <a href="{% url 'logout' %}">
            <input type="button" value="Logout"/>
        </a>
        {% else %}
        <h2>{{ message }}</h2>
        {% endif %}
    </body>

@KenWhitesell please guide me here as well, I don’t understand why it is not recognizing the user as I am accessing it from request instance.

What is the specific line that is throwing the error as indicated by the error message you are receiving?

@KenWhitesell the error is below:

AttributeError at /logout
'AnonymousUser' object has no attribute 'auth_token

and more details of error are below:

Traceback Switch to copy-and-paste view
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py, line 55, in inner
                response = get_response(request) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response
                response = wrapped_callback(request, *callback_args, **callback_kwargs) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py, line 54, in wrapped_view
        return view_func(*args, **kwargs) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py, line 84, in view
            return self.dispatch(request, *args, **kwargs) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 509, in dispatch
            response = self.handle_exception(exc) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 469, in handle_exception
            self.raise_uncaught_exception(exc) …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 480, in raise_uncaught_exception
        raise exc …
Local vars
C:\Users\Khubaib Khawar\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\views.py, line 506, in dispatch
            response = handler(request, *args, **kwargs) …
Local vars
C:\Users\Khubaib Khawar\Downloads\Meistery\Round2\backend_dev_trial_ass_r2\accounts\views.py, line 219, in get
        request.user.auth_token.delete() …
Local vars

Basically, there are multiple lines that are throwing exception, but the last of these lines is request.user.auth_token.delete().

I think it should work. I don’t see anything wrong in it. Don’t know why it is behaving like this.

I don’t know. I thought I had an idea where the problem may have been, but the full error message wasn’t what I guessed it might be. I suggest you check on one of the official DRF support channels.

It is not related to DRF. I am using the simple Django for logging in and logging out the user.

Your view is a subclass of APIView. If you can demonstrate this problem with a regular Django view, then I might take a closer look. But since it’s using DRF views, I suspect it’s a DRF related issue.

Let me do it in simple Django, then I will get back here with an update. Thanks.

Also keep in mind that token authentication is something generally used with DRF and not generally used with pure Django.

OK @KenWhitesell , then how does the user gets log in and log out in general Django without Token Authentication?

See Using the Django authentication system | Django documentation | Django

Seems that I will have to use general Django’s views, forms, and models to accomplish this.

The problem is you are deleting the token in logout view. It will delete the token permanently from database. That’s why you are getting anonymous user error.