Reputation: 188
I'm using djangorestframework in django==2.0 with python 3.7
I put an event like this
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
from rest_framework.authtoken.models import Token
Token.objects.create(user=instance)
when I tried to create a user the compiler giving an error:
Exception Value:
type object 'Token' has no attribute 'objects'
Upvotes: 3
Views: 2968
Reputation: 180
I just simply forgot to add
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
to my REST_FRAMEWORK variable
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
}
now, it should look like this:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
Also, dont forget to specify the authtoken module within the rest framework library, like so:
INSTALLED_APPS = [
'rest_framework',
'rest_framework.authtoken',
]
Upvotes: 0
Reputation: 921
Looks like the Token
model is not created. So make sure you followed the installation in the documentation.
Make sure you have 'rest_framework.authtoken'
in INSTALLED_APPS
Also, rest framework authentication classes inside settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
Also, make sure you do python manage.py makemigrations
and then python manage.py migrate
which create the Token
model
Upvotes: 1
Reputation: 231
First check whether you have added 'rest_framework.authtoken'
under INSTALLED_APPS in settings.py. Then run 'python manage.py migrate'.
Secondly you should open new python shell while creating token for users without token as follows:
>>> `from django.contrib.auth.models import User`
>>> `from rest_framework.authtoken.models import Token`
>>> `user = User.objects.get(pk=1)`
>>> `Token.objects.create(user=user)`
<Token: efa5fc4a8b142cd20478a7baaf9d763be44d6acc>
Upvotes: 0
Reputation: 1271
Try to do the following
>>> from rest_framework.authtoken.models import Token
>>> Token.objects.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: type object 'Token' has no attribute 'objects'
If the above error occurs, That's because you didn't add the auth token in the settings' INSTALLED_APPS. if it's not the in the INSTALLED_APPS, it's abstract and doesn't have the default manager (objects).
Upvotes: 1