如何在Django Rest Framework应用中修复`Forbidden`状态代码

时间:2019-04-16 18:24:39

标签: javascript python django vue.js django-rest-framework

我正在尝试在Django Rest Framework应用程序中实现登录功能。我遇到了一个问题,即使为所有人打开视图,DRF也会返回“禁止”状态代码。

我添加了装饰器@api_view和@permission_classes并试图更改其顺序

/breakdown/views.py

@api_view(['GET', 'POST', ])
@permission_classes((permissions.AllowAny,))
def sign_in(request):
    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)
    username = body['username']
    password = body['password']
    print(username, password)

    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            res = JsonResponse({"data": "1"})
            return Response("Success", status=HTTP_STATUS_OK)
        else:
            print("Error. Disabled account")
            return Response("Disabled account", status=410)
    else:
        print("invalid login")
        return Response("Invalid login", status=400)

breakdown / urls.py

urlpatterns = [
    path('user/surveys', survey.get_list_of_surveys),
    path('users/authenticate', sign_in),
]

src / _services / user.sevice.js

function login(username, password) {
  const requestOptions = {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({username, password})
  };
  console.log(requestOptions);
  return fetch(`http://127.0.0.1:8000/users/authenticate`, requestOptions)
    .then(handleResponse)
    .then(user => {
      if (user.token) {
        localStorage.setItem('user', JSON.stringify(user));
      }
      return user;
    });
}

GitHub链接https://github.com/Jlo6CTEP/students_breakdown/tree/mir_trud_may

我应该重定向到收到Forbidden消息的主页,并且当前页面没有更改。

0 个答案:

没有答案