Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I import the user model in Django and select all of the objects

When I use

from django.conf import settings

in my DjangoRestFramework views,

class UserList(ListCreateAPIView):
    queryset = settings.AUTH_USER_MODEL.objects.all()
    serializer_class = UserSerializer

my I receive the error

AttributeError at /users/

'str' object has no attribute 'objects'

Request Method:     GET
Request URL:    http://localhost:9999/users/
Django Version:     1.5.1
Exception Type:     AttributeError
Exception Value:    

'str' object has no attribute 'objects'
like image 802
user1876508 Avatar asked Jun 25 '13 19:06

user1876508


1 Answers

settings.AUTH_USER_MODEL is a string. It is not a model object.

You need to do something like this:

try:
    from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
    from django.contrib.auth.models import User
else:
    User = get_user_model()

Now,

queryset = User.objects.all()

-- OR --

if you are using only django 1.5, you can simply do:

from django.contrib.auth import get_user_model

queryset = get_user_model().objects.all()
like image 135
karthikr Avatar answered Sep 30 '22 22:09

karthikr