【问题标题】:Put request 403 error django restframework提出请求 403 错误 django restframework
【发布时间】:2019-01-30 01:44:39
【问题描述】:

我正在使用 redux 和 python django 和 django rest 框架创建一个带有 react-js 的 Web 应用程序。

我使用 JWT 进行身份验证。

我面临的问题是从前端发送请求时出现 403 错误。

我已经检查了后端所有配置都已设置但仍然出现此错误。

请检查以下代码。

型号:

class StatusQuerySet(models.QuerySet):
    pass

class StatusManager(models.Manager):
    def get_queryset(self):
        return StatusQuerySet(self.model,using=self._db)

class Apptype(models.Model):
    user        =   models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    appType     =   models.CharField(max_length=50)
    objects     =   StatusManager()

    def __str__(self):
        return self.appType

序列化器:

class AppTypeSeriializer(serializers.ModelSerializer):
    class Meta:
        model = Apptype
        fields = [
            'user',
            'id',
            'appType'
        ]
        read_only_fields = ['user','id']

观看次数

class AppTypeStatusAPIDetailView(
    mixins.UpdateModelMixin,
    mixins.DestroyModelMixin,
    generics.RetrieveAPIView):

    lookup_field            =   'id'
    permission_classes      =   [permissions.IsAuthenticatedOrReadOnly]
    serializer_class        =   AppTypeSeriializer
    queryset                =   Apptype.objects.all()


    def put(self,request, *args, **kwargs):
        print("Value of = ",request.data.get("appType"))
        return self.update(request, *args, **kwargs)
    def patch(self,request, *args, **kwargs):
        return self.update(request, *args, **kwargs)
    def delete(self,request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

网址

urlpatterns = [
    url(r'^appType/$',AppTypeStatusView.as_view()),
    url(r'^appType/(?P<id>\d+)/$',AppTypeStatusAPIDetailView.as_view()),
 ]

权限

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',

    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

JWT_AUTH = {
    'JWT_ENCODE_HANDLER':
    'rest_framework_jwt.utils.jwt_encode_handler',

    'JWT_DECODE_HANDLER':
    'rest_framework_jwt.utils.jwt_decode_handler',

    'JWT_PAYLOAD_HANDLER':
    'rest_framework_jwt.utils.jwt_payload_handler',

    'JWT_PAYLOAD_GET_USER_ID_HANDLER':
    'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',

    'JWT_RESPONSE_PAYLOAD_HANDLER':
    'rest_framework_jwt.utils.jwt_response_payload_handler',

    'JWT_ALLOW_REFRESH': True,
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),

    'JWT_AUTH_HEADER_PREFIX': 'JWT',
    'JWT_AUTH_COOKIE': None,
}

动作触发时的前端代码。

export const updateAppTypeData = (appData) => async dispatch => {
  const token = localStorage.getItem('token')
  console.log(token)

  const headers = {
    "Content-Type": "application/json",
    "Authorization": "JWT "+ token,
  }
  const data =  {"appType":"Kilo"} // Custom send
  const response = await axios.put('http://localhost:8000/api/posts/appType/1/',JSON.stringify(data),headers)
  //dispatch({ type : FETCH_APP_TYPE , payload: response.data });
};

错误:

【问题讨论】:

  • 在浏览器的Network 选项卡中检查请求的请求标头。
  • @ja6fa7jq 您是否尝试过使用 POSTMAN 等 REST 工具?
  • 感谢@Sachin,您的评论和回答帮助了我。令牌即将过期,我一次又一次地发送过期的令牌,发送请求的方式也是错误的。

标签: python django reactjs django-models django-rest-framework


【解决方案1】:

这个设置适合我,

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': (  
       'rest_framework.authentication.BasicAuthentication', 
       'rest_framework.authentication.TokenAuthentication',
       'rest_framework.authentication.SessionAuthentication',

   ),

Viewauthentication_classes,authentication_classes 应该是元组,所以如果你使用一个身份验证类,请确保在最后使用“,” authentication_classes = (TokenAuthentication,)

class MainPollVoteByUser(viewsets.ViewSet):
    serializer_class = MainPollVoteSerializer
    permission_classes = [IsOwnerOrReadOnly, IsAuthenticated]
    authentication_classes = (TokenAuthentication,SessionAuthentication)

【讨论】:

    【解决方案2】:

    我认为您使用的 axios.put 方法错误。
    您需要传递包含一个名为 headers 的键的配置。您目前正在将标题直接作为第三个参数传递。

    解决方案

    axios.put(
      'http://localhost:8000/api/posts/appType/1/',
      JSON.stringify(data),
      {
          headers: headers
      }
    )
    

    【讨论】:

    • 谢谢@Sachin。我为此挣扎了两天。你的帮助很大。
    猜你喜欢
    • 2018-08-06
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    • 2017-10-07
    相关资源
    最近更新 更多