Home > Back-end >  Django, request.user prints AnonymousUser, even if i logged in
Django, request.user prints AnonymousUser, even if i logged in

Time:04-11

views.py

class StorageView(viewsets.ModelViewSet):
    serializer_class = StorageSerializer

    def get_queryset(self):
        if self.request.user.is_authenticated:
            user = self.request.user
            queryset = Storage.objects.filter(username=user.username)
            return queryset
        else:
            print(self.request.user)
            return []

urls.py

from django.urls import path, include
from django.urls import re_path as url

urlpatterns = [
    path('auth/', include('rest_auth.urls')),
    path('auth/register/', include('rest_auth.registration.urls'))
]

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # CORS
    'corsheaders',
    # REST
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    'rest_auth.registration',
    'django.contrib.sites',
    # App
    'backend'
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

SITE_ID = 1
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_UNIQUE_EMAIL = True

REST_FRAMEWORK = {    
    'DATETIME_FORMAT': "%m/%d/%Y %I:%M%P",    
    'DEFAULT_AUTHENTICATION_CLASSES': [        
    'rest_framework.authentication.TokenAuthentication',    
    ],
}

I logging in via form or api, but is_authenticated method don't see me

Login via api postman screenshot

Condition in get_queryset() function in views.py always evaluates to false, even if i logged in it keeps printing "AnonymousUser", why? How to check if user is logged in, in my case?

CodePudding user response:

Provide

permission_classes = [IsAuthenticated]

in your views.

and pass

Authorization token with every request

axios
  .get(
    `http://localhost:8000/anything`,
    {
      headers: {
        Authorization: `Token ${token}`,
      },
    }
  )
  • Related