放置请求403错误Django RestFramework

时间:2018-08-23 15:57:26

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

我正在使用redux创建带有react-js的Web应用程序,并在django rest框架中使用python django创建后端。

我正在使用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)

URL

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 });
};

错误:

enter image description here

2 个答案:

答案 0 :(得分:1)

我认为您错误地使用了axios.put方法。
您需要传递包含名为adict = {0: {'Fantasy': 6, 'Animation': 1, 'Family': 2, 'Action': 6, 'Comedy': 1, 'Adventure': 8}, 1: {'Fantasy': 1, 'Drama': 1, 'Adventure': 9, 'Action': 10, 'Thriller': 1, 'Comedy': 1, 'Romance': 1, 'Science_Fiction': 10}, 2: {'Fantasy': 8, 'Animation': 2, 'Adventure': 16, 'Thriller': 3, 'Drama': 1, 'Comedy': 1, 'Family': 4, 'Science_Fiction': 11, 'Horror': 1, 'Action': 15}, 3: {'Fantasy': 1, 'Adventure': 5, 'Thriller': 4, 'Comedy': 1, 'Science_Fiction': 2, 'Crime': 3, 'Action': 6}, 4: {'Animation': 2, 'Fantasy': 5, 'Adventure': 5, 'Action': 4, 'Comedy': 1, 'Family': 4, 'Romance': 1}, 5: {'Fantasy': 1, 'Western': 1, 'Family': 2, 'Adventure': 4, 'Thriller': 3, 'Drama': 3, 'Science_Fiction': 1, 'Romance': 1, 'Crime': 1, 'Animation': 2, 'Action': 5}} 的密钥的配置。您当前正在直接将标头作为第三个参数传递。

解决方案

{'Fantasy': 6 , 'Western': 1, 'Family':4 ...}

答案 1 :(得分:0)

此设置对我有用

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

   ),

Viewauthentication_classes,authentication_classes应该是tupple,因此,如果您使用一个身份验证类,请确保在末尾使用“,” authentication_classes =(TokenAuthentication,)

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