0

i'm a newbie of django-rest-framework, i try a very simple web app

one programe

url.py

urlpatterns = [
    url(r'^admin/$', "app.views.admin_index"),
]

views.py

def admin_index(request):
    print request
    print type(request.user)    
    return render(request, "admin/index.html")

output is

AnonymousUser
<class 'django.utils.functional.SimpleLazyObject'>

anthoner programe

url.py

urlpatterns = [
    url(r'^admin/$', AdminViewSet.as_view({'get':'list'})),
]

views.py

class AdminViewSet(viewsets.ViewSet):
    permission_classes = (permissions.IsAdminUser,)
    renderer_classes = (renderers.TemplateHTMLRenderer,)    
    def list(self, request):
        print request
        print type(request.user)
        return Response(template_name='admin/index.html')

output is

admin
<class 'django.contrib.auth.models.User'>

so, request.user has two different output, most important is one is AnonymousUser another one is admin, why? something wrong?

=========solution========================

settings.py

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny'
    ),

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )    
}

it has 'rest_framework.authentication.BasicAuthentication', so it make request.user store in http header, but not in session, so django.contrib.auth's logout failed.

solution is only use 'rest_framework.authentication.SessionAuthentication'

lsaturn
  • 145
  • 1
  • 11

1 Answers1

1

class 'django.utils.functional.SimpleLazyObject' is a type of promise. When evaluated, it will act as a proxy to the delayed object. There's nothing wrong here; django uses this type in a lot of places to implement laziness.

Marcin
  • 48,559
  • 18
  • 128
  • 201
  • you are right, i read this http://stackoverflow.com/questions/10506766/django-purpose-of-django-utils-functional-simplelazyobject, but i'm more care about different value, it made me hard to evaluate whether logined – lsaturn Oct 23 '14 at 23:47
  • 1
    You should check `user.is_active` and `user.is_authenticated` to determine if the user is authenticated, not by doing type checking – Kevin Brown-Silva Oct 24 '14 at 02:24