Hi I am trying to use TokenAuthentication from Django rest-framework.
I am able to use this with my views with rest api.
#view_rest.py
class CartList(generics.ListCreateAPIView):
serializer_class = CartSerializer
filter_class = CartFilter
permission_classes = (permissions.IsAuthenticated,)
def create(self, request, *args, **kwargs):
request.data['user_id'] = request.user.id
return generics.ListCreateAPIView.create(self, request, *args, **kwargs)
def get_queryset(self):
user = self.request.user.id
return Cart.objects.filter(user_id_id=user)
But In my custom views it is not authenticating,
#custom_django_views.py
@login_required(login_url='/login/')
def order(request):
'''Returns page to place order
'''
return render(request,"order.html",{})
#this will redirect me to login page.
#settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'myapp',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'site_aggrigator.middleware.SubdomainMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
#rest framework
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': (
'rest_framework.filters.DjangoFilterBackend',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.DjangoObjectPermissions',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
I am not able to understand why request for custom_django_views, is not authenticated? When does authentication happens?
The use case is wrong. Django rest framework doesn't allow these things. http://www.django-rest-framework.org/topics/ajax-csrf-cors/#javascript-clients
Session authentication should be used for web browser. And they are not required when using it for mobile.
Rest framswork views take care of csrf validation when using token authentication.
This worked for me.
from rest_framework.decorators import api_view
@api_view(["GET"])
def your_function(request):
pass
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.