3

I am learning both Django and the Django REST framework. I had this error before and fixed it. Now, this problem rears its head again.

This is the error I get when trying to get an auth token:

'module' object has no attribute 'views'

and this is my urls.py:

from django.conf.urls import include, url
import rest_framework
from rest_framework import authtoken
from . import views

urlpatterns = [
    url(r'^games/$', views.GameList.as_view()),
    url(r'^games/(?P<pk>[0-9]+)/$', views.GameDetail.as_view()),
    url(r'^users/$', views.UserList.as_view()),
    url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
    url(r'^api-token-auth/', authtoken.views.obtain_auth_token),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

Somehow it can't find authtoken.views. Annoying thing is, this worked fine until I restarted with manage.py runserver.

1
  • I have updated my answer. Does that not work for you? Commented Jan 4, 2016 at 21:51

2 Answers 2

10

The reason it doesn't work - authtoken is a package - when you import it, it does not contain what you want -

>>> from rest_framework import authtoken
>>> dir(authtoken)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']

You can see that authtoken does not contain anything useful. However the view you are interested in is actually inside the views module.

So we can first change the import to:

from rest_framework.authtoken import views as authviews

Then use it in the urlconf:

url(r'^api-token-auth/', authviews.obtain_auth_token),
Sign up to request clarification or add additional context in comments.

2 Comments

Care to explain the downvote? The doc uses the same syntax -- django-rest-framework.org/api-guide/authentication
Didn't seem to be sufficient enough for OP ;-) And of course it got downvoted too!
2

I was facing same error, but I realized that below thing.

You need to add rest_framework.authtoken to your INSTALLED_APPS, And don't forget to python manage.py migrate

2 Comments

Also, take care of order of adding... Add after rest_framework. If u add before it then it will give error. I had this sick issue for 30min :/
@Omkar i tried this but I'm getting the error: AttributeError: module 'rest_framework' has no attribute 'authtokendemo' my entry into INSTALLED_APPS is [...,'rest_framework', 'rest_framework.authtoken', ...]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.