Reputation: 369
I'm trying to retrieve a token via the django rest framework My api.views.py looks like this
from rest_framework.views import APIView
from rest_framework import status
from rest_framework import parsers
from rest_framework import renderers
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.serializers import AuthTokenSerializer
class ObtainAuthToken(APIView):
throttle_classes = ()
permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)
serializer_class = AuthTokenSerializer
model = Token
def post(self, request):
serializer = self.serializer_class(data=request.DATA)
if serializer.is_valid():
token, created = Token.objects.get_or_create(user=serializer.object['user'])
return Response({'token': token.key})
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
my url looks like:
url(r'^api-token-auth/$', ObtainAuthToken.as_view())
When I request the auth token, I don't get a response and I get a 302 status code I am requesting the token with curl:
curl -X POST -d "username=admin&password=pass" http://localhost:8000/api-token-auth/
Am I getting redirected? Any help would be appreciated, thank you.
Upvotes: 0
Views: 2781
Reputation: 1485
Have you checked the value of APPEND_SLASH to see if that is doing it, from djangos docs:
https://docs.djangoproject.com/en/dev/ref/settings/#append-slash
Default: True
When set to True, if the request URL does not match any of the patterns in the URLconf and it doesn’t end in a slash, an HTTP redirect is issued to the same URL with a slash appended. >Note that the redirect may cause any data submitted in a POST request to be lost.
The APPEND_SLASH setting is only used if CommonMiddleware is installed
The other thing to check is that you are using curl as you expect, try the following command:
curl --data "username=xxx&password=xxx" http://localhost:8000/api/token-auth/
As an aside from the docs:
http://www.django-rest-framework.org/api-guide/authentication#tokenauthentication
We can keep things a little cleaner by adding just the following to your url patterns:
urlpatterns += patterns('',
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')
)
It also says further down that page:
If you need a customized version of the obtain_auth_token view, you can do so by overriding the ObtainAuthToken view class, and using that in your url conf instead.
You could do that by doing something like this:
from rest_framework.authtoken.views import ObtainAuthToken
class ModifiedObtainAuthToken(ObtainAuthToken):
pass
modified_obtain_auth_token = ModifiedObtainAuthToken.as_view()
and then adding something like:
urlpatterns += patterns('',
url(r'^api-token-auth/', 'yourapp.views.modified_obtain_auth_token')
)
Upvotes: 1