您好我正在尝试使用Django rest-framework中的TokenAuthentication。
我可以将这个用于我的观点与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)
但在我的自定义视图中,它不是身份验证,
#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',
)
}
我无法理解为什么对custom_django_views的请求未经过身份验证?身份验证何时发生?
答案 0 :(得分:0)
用例错了。 Django休息框架不允许这些东西。 http://www.django-rest-framework.org/topics/ajax-csrf-cors/#javascript-clients
会话身份验证应该用于Web浏览器。使用它进行移动时不需要它们。
使用令牌身份验证时,休息框架视图会处理csrf验证。
答案 1 :(得分:0)
这对我有用。
from rest_framework.decorators import api_view
@api_view(["GET"])
def your_function(request):
pass